Javascript:使用Object literal时,属性的排序是否重要? [英] Javascript: when using Object literal, does ordering of properties matters?
问题描述
采用以下示例:
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()方法移到对象声明的顶部。
Now I am moving the getInfo() method at the top of my object declaration.
var apple = {
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
},
type: "macintosh",
color: "red",
};
apple.getInfo();
red macintosh apple
我原本期待javascript解析器/编译器失败,因为这个。 color和this.type尚未定义。这是如何在内部工作的?
I was expecting the javascript parser/compiler to fail, since this.color and this.type are not yet defined. How does this work internally ?
(这个问题最初是一个ExtJS框架问题: ExtJS:通过原型上的函数设置属性:它是一种安全模式吗? / a>,但我意识到这是一个更普遍的javascript问题,因此这个新问题)
( this question was originally a ExtJS framework question here: ExtJS: settings properties via a function on the Prototype: is it a safe pattern?, but I realized it is a more general javascript question, hence this new one)
推荐答案
函数内的代码直到你调用它才会被执行,所以
的属性这个
直到调用apple.getInfo()
。
The code inside the function is not executed until you call it, and so the property color
of this
is not evaluated until apple.getInfo()
is called.
编辑:
var apple = {
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
},
type: "macintosh",
color: "red",
}
}
此时定义了apple对象,
getInfo
属性是在评估时将返回属性``的函数
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();
现在评估该函数,并且属性
color
和类型
此时已明确定义
该函数在求值时获取这些属性的值,以便在属性 color
和时输入
被更改,函数的返回值也会改变。
The function obtains the values of these properties when it is evaluated so that if the properties color
and type
are changed, the return value of the function changes too.
这篇关于Javascript:使用Object literal时,属性的排序是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!