gpt4 book ai didi

javascript - 将不同的 this 作用域绑定(bind)到 ES6 => 函数运算符

转载 作者:数据小太阳 更新时间:2023-10-29 04:30:55 24 4
gpt4 key购买 nike

在尝试使用 ES6 提供的 => 特性继承上下文后,我注意到 this 上下文永远无法更改。示例:

var otherContext = {
a: 2
};
function foo() {
this.a = 1;

this.bar = () => this.a;

}

var instance = new foo;
instance.bar(); // returns 1
instance.bar.bind(otherContext)(); // returns 1

没有 => 运算符并使用 function 关键字:

function foo() {
this.a = 1;

this.bar = function () {
return this.a;
}
}
var instance = new foo;
instance.bar(); // returns 1
instance.bar.bind(otherContext)(); // returns 2

因此,如果我们从外部调用接收到一个函数,或者只是在一个变量中有一个函数,我们如何确定我们是否能够将一个不同的 this 绑定(bind)到它,或者它是否只是从在什么地方?

javascript 什么都不告诉你,这听起来很危险,一个人可能会陷入一个非常微妙和困难的错误。

最佳答案

它实际上只是 bind 的新语法,因此不会引入任何新的陷阱。

var otherContext = {
a: 2
};
function foo() {
this.a = 1;
this.bar = function () { return this.a }.bind(this);
}

var instance = new foo;
log(instance.bar()); // returns 1
log(instance.bar.bind(otherContext)()); // returns 1

function log(value) {
document.body.appendChild(
document.createTextNode(value)
);
}

Therefore, if we receive a function from an external call or just have a function in a variable, how can we be sure if we are going to be able to bind a different this to it or if it will just inherit it from somewhere?

因为:

  1. 您将首先编写该函数
  2. 您将编写一个关于如何调用您的函数的规范,以便人们知道在您选择的上下文中传递一个使用 this 的函数。

关于javascript - 将不同的 this 作用域绑定(bind)到 ES6 => 函数运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33284596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com