Javascript:使用对象文字时,属性的顺序是否重要?

标签 javascript prototype

以下面的例子为例: 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 and type have clearly already been defined at this point

函数在计算时获取这些属性的值,因此如果属性 colortype 发生变化,函数的返回值也会发生变化。

关于Javascript:使用对象文字时,属性的顺序是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32269428/

相关文章:

javascript - 如何过滤掉数组中重复的对象?

javascript - MediaElement 播放器 "success"回调未被执行,如果使用 Flash 回退,则 "ended"事件可能不会触发

oop - 在函数式编程中实现多态性

javascript - 性能:原型(prototype)私有(private)方法

namespaces - Perl:匿名子程序中的原型(prototype)

javascript - 在 puppeteers 监听器 page.on 的回调之外捕获错误

javascript - 在 VI 中保存文件后如何刷新网络浏览器

Javascript 添加前导零到日期

javascript - 调用 javascript 原型(prototype)方法时未定义的函数

javascript - 我们真的需要一个函数对象来在 JavaScript 中应用原型(prototype)方法吗?如果是的话,为什么?