为什么这样不好呢?
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};
var some$Other$Function = function() {
alert('Yo yo yo');
};
var c = new aContract();
c.someFunction();
c.someOtherFunction();Firebug说c.someOtherFunction不是一个函数
但是这个工作得很好。
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};
function some$Other$Function() {
alert('Yo yo yo');
};
var c = new aContract();
c.someFunction();
c.someOtherFunction();我错过了什么?我更喜欢使用第一种方法在javascript中编写代码,这种方法通常工作得很好,但在我创建原型时似乎不能正常工作。
谢谢,~ck in Sandy Eggo
发布于 2009-06-26 23:22:15
在实际创建some$Other$Function之前,您已经将some$Other$Function分配给了aContract.prototype.someOtherFunction。语句的顺序很重要。如果你改变事情的顺序,你会做得很好:
var some$Other$Function = function() {
alert('Yo yo yo');
};
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};发布于 2009-06-26 23:22:34
在对其进行评估时:
aContract.prototype = { ... }这还没有经过评估:
var some$Other$Function = function() { ... }因此,aContract.prototype.someOtherFunction被设置为undefined。
第二个方法之所以有效,是因为函数声明(第二个是表达式,第一个是表达式)在任何其他语句之前进行计算。这里有更多细节:Named function expressions demystified
发布于 2009-06-26 23:22:52
这是由于吊装造成的。函数语句被移到其作用域的顶部。
编辑:验证克罗克福德的JavaScript:好的部分第113页。
https://stackoverflow.com/questions/1051666
复制相似问题