以下面的例子为例: http://www.phpied.com/3-ways-to-define-a-javascript-class/
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
};
现在我将 getInfo() 方法移到对象声明的顶部。
var apple = {
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
},
type: "macintosh",
color: "red",
};
apple.getInfo();
red macintosh apple
我原以为 javascript 解析器/编译器会失败,因为 this.color 和 this.type 尚未定义。这在内部是如何工作的?
(这个问题最初是这里的 ExtJS 框架问题:ExtJS: settings properties via a function on the Prototype: is it a safe pattern?,但我意识到这是一个更一般的 javascript 问题,因此是这个新问题)
最佳答案
函数内的代码直到您调用它才会执行,因此 this
的属性 color
直到 apple.getInfo()< 才会被评估
被调用。
编辑:
var apple = {
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
},
type: "macintosh",
color: "red",
}
}
At this time the apple object is defined, and the
getInfo
property is a function that will return the properties ``when it is evaluated
apple.getInfo();
The function is now evaluated, and the properties
color
andtype
have clearly already been defined at this point
函数在计算时获取这些属性的值,因此如果属性 color
和 type
发生变化,函数的返回值也会发生变化。
关于Javascript:使用对象文字时,属性的顺序是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32269428/