Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript “this”不引用调用它的上下文(对于箭头函数)_Javascript_Javascript Objects - Fatal编程技术网

Javascript “this”不引用调用它的上下文(对于箭头函数)

Javascript “this”不引用调用它的上下文(对于箭头函数),javascript,javascript-objects,Javascript,Javascript Objects,这个上下文并没有像预期的那样工作。我在下面的代码中将我的问题描述为注释 const dog = { //arrow function bark: () => { console.log(this); }, makeBark(){ // this here refers to the dog object // (as it is a normal function) // so insid

这个上下文并没有像预期的那样工作。我在下面的代码中将我的问题描述为注释

const dog = {

    //arrow function
    bark: () => {
        console.log(this);
    },

    makeBark(){
        // this here refers to the dog object
        // (as it is a normal function) 
        // so inside the bark function , shouldn't
        // this refer to the dog object ?  
        this.bark();
    },    

};        

dog.makeBark(); // this is the problematic function
我不明白为什么dog.makeBark打印窗口对象。bark函数的父作用域是dog对象

this of arrow函数将是其父作用域的this,其中声明的this不是调用的this


在上面的示例中,您只是从另一个函数调用了bark。此代码不会更改树皮的此属性。此外,对于arrow函数,此值在整个代码中保持不变,并且永远不能隐式或显式更改

你能描述一下你对这个函数有什么问题吗?你期望得到什么?arrow函数永远不会使用除了这个词以外的任何东西。不管你怎么称呼它,记住箭头函数是词汇绑定的。对象初始化期间的词法作用域不是对象。@Quentin我不认为它是重复的,因为OP已经知道它打印窗口对象的原因。他在第三部分被搞糊涂了父作用域不是狗对象吗?@tilakmady对象不能是作用域。一般来说,你是如何找到作用域的?@tilakmady我想说作用域是你可以写语句的地方。在上面的帖子中,我提到的范围是指功能。我使用scope这个词是因为还有全局范围。但是除了上面的文章中的全局作用域之外,我指的是函数。那么,声明了arrow函数的父函数是什么呢?