不久前我拿起这本书来帮助理解如何将我对 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);
}