这个内部对象方法的价值? [英] Value of this inside object method?

查看:65
本文介绍了这个内部对象方法的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用箭头函数调用函数时,我对this的值感到非常困惑.让我们以我的例子为例:

I very confusing about the value of this at the moment of an invocation function using arrow functions. Let's take my example:

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

当我将此代码放在浏览器控制台上时,发生了一件有趣的事情,func1()将按预期输出5 *,但是当我运行func2时,我得到了undefined.这里发生了什么?为什么func2中的this的值引用全局对象(在本例中为Window).

When i put this code on the browser console, an interesting thing happens, func1() will output 5 as expected *, but when i run func2 i got undefined. What is going on here? Why the value of this inside func2 makes reference to the global object(Window in this case).

我认为我期望该输出,因为它是这样工作的,这就是Alan和slevetman解释此处中.但是根据 Jason的解释

I think i expect that output, because it is how it works, thats the reason why Alan and slevetman explains here and here respectively. But according to the Jason's explanation

箭头函数没有自己的此值.箭头函数中的this的值始终是从封闭范围继承的.

Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.

那么,为什么在func2内部的this的值不继承其封闭范围obj的值?

So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?

推荐答案

那么,为什么在func2内部的this的值不继承其封闭范围obj的值?

So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?

此处的obj不是封闭"范围.您要定义obj的范围是封闭"范围.

The obj here is not the "enclosing" scope. The scope that you are defining the obj in is the "enclosing" scope.

请考虑以下示例:

var obj = {
  property: 5,
  func1: function () {
      let func2 = () => {
        console.log(this.property); 
      }
      func2();
  },
}
obj.func1(); // logs 5
obj.func1.call({
   property: 6
}) // logs 6

当调用内部func2时,this关键字将obj引用为obj,而包装器func1函数中的this引用了objfunc2 继承 this值.内部箭头功能不会绑定其自己的this值.

When the inner func2 is called, the this keyword refers to the obj as this in the wrapper func1 function refers to the obj and the func2 inherits the this value. The inner arrow function does not bind it's own this value.

这篇关于这个内部对象方法的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆