javascript this闭包的外部功能具有绑定的"this" [英] javascript this of the outer function of closure having a bound 'this'

查看:91
本文介绍了javascript this闭包的外部功能具有绑定的"this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解这一点. 我知道作用域链,javascript中的回调,回调中 this 的值,以及箭头功能.

I am having trouble to get my head around this one. I am aware of scope chaining, callbacks in javascript, the value of this in the callbacks and hence the arrow functions.

在javascript中,闭包可以通过作用域链访问封闭函数的变量.那么,为什么闭包不通过Function.prototype.bind访问闭包的父函数的'this'绑定呢?变量"this"是否不是作用域链的一部分?

In javascript, closures have access to variables of the enclosing function via the scope chain. So why the closure does not access the 'this' bound via Function.prototype.bind to the parent function of closure ? Is the variable 'this' not a part of the scope chain?

在chrome控制台中运行以下代码:

Ran the following code inside the chrome console :

a = 4;
b = 6;
function outer(){
    function inner(){
        console.log(`this.a is ${this.a} and this.b is ${this.b}`);
    }
    inner();
}
outer.bind({a:1,b:3})()

然后控制台又退回了:

this.a is 4 and this.b is 6

推荐答案

此和闭包是JS中的2种不同机制,不应混用. 外部函数中的this与内部函数中的this完全分开.

This and closures are 2 different mechanisms in JS and should not be mixed. this in outer function is completely separated from this in inner function.

在您的示例中,您期望内部函数具有此词法作用域的外部作用域,而这并不是它的工作方式.如果您使用的是箭头函数,则它的工作方式就像是这样,因为这将是词法的,并且将从外部函数指向此函数. 如果将内部函数更改为箭头函数,则可以观察到////this.a为1,this.b为3

In your example you are expecting for inner function to have lexical scope of this from outer function and that is just not how this is working. It is working like that if you are using arrow function because then this would be lexical and will point to this from outer function. if you change your inner function to arrow function you can observe that behavior // this.a is 1 and this.b is 3

const内部=()=> { console.log(this.a is ${this.a} and this.b is ${this.b}); };

const inner = () => { console.log(this.a is ${this.a} and this.b is ${this.b}); };

如果您想了解它的表现,我强烈推荐凯尔·辛普森(Kyle Simpson)着书,该书可在github

if you want to learn how this is behaving I highly recommend book from Kyle Simpson and it's free on github this & object prototypes

从书中.

要了解此绑定,我们必须了解调用位置:代码在函数中被调用的位置(而不是在声明位置).我们必须检查呼叫站点以回答问题:这是指什么?

因此,您可以看到内部函数的位置与其绑定的内容无关. 规定定义如何绑定

So like you can see position of inner function is not relevant to what this will bound to. rules that defines how this will be bound

阅读上面的链接后,您应该在JS中对此有更多的了解.

after reading above link you should have more understanding on this in JS.

这篇关于javascript this闭包的外部功能具有绑定的"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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