前一段时间我选择了this book来帮助理解如何将我在Java中的设计模式知识应用到Web开发中。但是,我在介绍中遇到了一个奇怪的差异。
作者声明以下代码定义了一个允许用户创建动画对象的类:
//Anim class
var Anim = function(){ /*code here*/ };
Anim.prototype.start = function(){ /*start code here*/ };
Anim.prototype.stop = function() { /*stop code here */};
//create a new Anim object and call the start method
var newAnim = new Anim();
newAnim.start();
我尝试了与我的应用程序类似的东西。
//Nucleus class and addLink function
var Nucleus = function(){
this.location=null;
this.links = [];
}
//revamp object and add to link array
Nucleus.prototype.addLink = function(marker){ }
上述类通过
实例化为全局变量var curSpot = new Nucleus();
但是,Firebug在页面加载时抛出错误,指出Nucleus is not a constructor
,并且禁用了Javascript按钮处理功能。通过将Nucleus
定义更改为
function Nucleus(){ /*instance members here*/ }
现在OO功能正常运行。为什么后一个例子有用,但这本书的例子会引发错误?
应Ryan Lynch的要求,发布了更多代码。这是使用1curStop的唯一代码。作为一个全局变量,
//global variables
var curStop = new Nucleus();
function showMarkers(){
//unreleated code here
var tourList = [];
//handles a double click event, adds current marker to list and creates one
//if not null. Otherwise, create a new Nucleus object and add current location
(function(marker){
google.maps.event.addListener(marker, 'dblclick', function(){
if (curStop != null){
tourList.push(curStop);
curStop = null;
} else {
curStop = new Nucleus();
curStop.addLocation(marker);
}
}); //end listener
})(marker);
}
function postTour(){
//need CurStop to be a global variable, since only new double-click events add the
//object to the tourList array. This makes sure that all objects are saved on
//button click
tourList.push(curStop);
}