首页 > 解决方案 > 对象字面量中的范围

问题描述

为什么在示例一中未定义,但在示例二中定义?我认为箭头符号将允许绑定在更高的范围内,在这种情况下是对象文字。

示例 1:

var runApp = {
    init: () => {
         console.log(this); //this is an empty object.  
         this.run() //will crash here, run not a function of this.
    },
    run: () => { 
         console.log("It's running!");
    }
};

// Now we call init
runApp.init();

示例 2:

var runApp = {
    init: function(){
         console.log(this);   
         this.run()
    },
    run: function() { 
         console.log("It's running!");
    }
};

// Now we call init
runApp.init();

标签: javascript

解决方案


这是因为您使用的是箭头功能。箭头函数将始终保持其语法定义的上下文。在您的示例中,这很可能是init未定义函数的窗口或全局对象。

非箭头函数将根据它们被引用的对象动态确定上下文。除非上下文已在.bind较早时明确设置为低谷,或者低谷.apply.call在调用站点。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this


推荐阅读