javascript – 将此范围绑定到ES6 => function operator

前端之家收集整理的这篇文章主要介绍了javascript – 将此范围绑定到ES6 => function operator前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在尝试使用=>继承上下文之后ES6给我们的功能我注意到这个上下文永远不会改变.
例:
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

因此,如果我们从外部调用接收函数或者只是在变量中有函数,我们怎样才能确定我们是否能够将不同的函数绑定到它或者它是否只是从某个地方继承它?

javascript没有告诉你任何事情听起来很危险,人们可能会因为一个非常微妙和困难的bug而陷入困境.

解决方法

它实际上只是bind的新语法,所以这并没有引入任何新的getchas方式.
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?

因为:

>您将首先编写该功能或>您将编写一个关于如何调用函数的规范,以便人们知道传入一个函数,该函数从您选择的上下文中使用它.

原文链接:https://www.f2er.com/js/158585.html

猜你在找的JavaScript相关文章