2012-09-24 69 views
1

例如:如何将对象引用传递给另一个对象?

JS文件:

function Controller() { 
self = this; 

self.createObject = createObject; 
    function createObject() { 
    new ObjectTest(self); 
    } 

self.createAlert = createAlert; 
function createAlert(text) { 
    alert(text); 
} 
} 

function ObjectTest(controller) { 
this.controller = controller; 
this.controller.createAlert("test"); 
} 

HTML文档 - 对象被构造并执行

<body onload="new Controller.createObject()"> 

这将给出该错误消息的方法:

Uncaught TypeError: Object #<Controller> has no method 'createAlert' 

回答

3

当构建一个实例,你需要添加括号:

<body onload="new Controller().createObject()"> 

但是你可以简化您的控制器,并使用更多的标准结构:

function Controller() { 
self = this; 
self.createObject = function(){ 
    new ObjectTest(self); 
}; 
self.createAlert = function(text) { 
    alert(text); 
}; 
} 
0

您的代码被解释为一个命名空间,所以它试图创建一个Controller.createObject函数的实例(没有)。括号中的一切,你想

(new Controller).createObject() 
// or 
new Controller().createObject() 

,而不是

new Controller.createObject() 
// which is like 
new (Controller.createObject)() 
0

Controller后错过了括号。您写道:

<body onload="new Controller.createObject()"> 

这基本上意味着“创建Controller.createObject一个新的实例”,你的意思“创建Controller一个新实例,然后调用createObject()

<body onload="new Controller().createObject()"> 

而且,看起来Controller更像是单身人士或“静态班”。其实你可以避免创建一个新的实例,然后,只用一个简单的对象:

var Controller = { 
    createObject: function() { 
     return new ObjectTest(this); 
    }, 

    createAlert: function(text) { 
     alert(text); 
    } 
} 

,然后从代码:

<body onload="Controller.createObject()"> 

希望它能帮助。

相关问题