在尝试使用=>继承上下文之后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?
因为:
>您将首先编写该功能或>您将编写一个关于如何调用函数的规范,以便人们知道传入一个函数,该函数从您选择的上下文中使用它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。