将此范围与ES6 =>函数运算符 [英] Binding different this scope to ES6 => function operator
问题描述
在使用ES6给我们的=>功能继承上下文后,我注意到这个上下文永远不会被改变。
示例:
After experimenting with inheriting contexts with the => feature that ES6 gives us I noticed that the this context can never be changed. Example:
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关键字:
Without the => operator and using the function keyword:
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
因此,如果我们从外部调用中接收到一个函数,或者只有一个函数一个变量,我们怎么能确定我们能够绑定一个不同于它的东西,还是从某个地方继承?
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?
这听起来很危险这个javascript并没有告诉你什么,一个人可能会陷入一个非常微妙和困难的bug。
It sounds dangerous that javascript does not tell you anything, one might fall for a VERY subtle and difficult bug.
推荐答案
对于 bind
,所以这不会引起任何新的陷阱的方式。
It is effectively just new syntax for bind
, so this doesn't introduce anything new in the way of gotchas.
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?
因为:
- 您将首先编写该功能或
- 您将会写一个关于如何调用你的函数的规范,以便人们知道从你选择的上下文中传递使用
这个
的函数。
- You'll have written that function in the first place or
- You'll have written a specification for how to call your function so that people know to pass in a function which makes use of
this
from a context you choose.
这篇关于将此范围与ES6 =>函数运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!