在其中一个博客中,我了解到.bind()
只会将传递的对象严格绑定到这个'其中.call()
将执行该功能。但是,将.call()
分配给其他变量将实现相同的目的。我试图理解为什么.bind()
被引入或者我错过了什么?
以下代码证明了我上面所说的内容:
function foo () {
console.log( this.a );
}
let obj = {
a: 2,
foo: foo
};
let a = 'oops! global';
let foocall = foo.call (obj);
let foobind = foo.bind (obj);
foo.call (obj);
setTimeout ( foocall , 100);
setTimeout ( foo , 100);
输出:
[xyz:〜/ sandboxes / js] $ node --use-strict binding.js 2 2 2
答案 0 :(得分:5)
但是,将.call()分配给其他变量将达到同样的目的。
没有。我不知道你在哪里阅读,但这是完全错误的。分配call
的结果将分配调用函数的结果。它没有做bind
所做的事情。
在您的代码中,foocall
为undefined
。为什么?因为您已调用 foo
并将其返回值分配给foocall
。由于foo
从未使用return
值,因此调用foo
的结果为undefined
。
call
调用该函数(线索名称为:-)),设置值this
将在调用期间拥有。
bind
不调用该函数,它会返回一个新函数,在调用时,将调用原始函数并将this
设置为特定值(并且可选初始参数,如果您在调用this
时提供bind
值之外的那些参数。
这些链接是MDN(我曾经链接到规范,当规范对普通人来说是可理解的时候),这有进一步的解释和例子。 (感谢您提醒,Oskar!)
这是一个更正的例子:
function foo(label) {
snippet.log(label + ", " + this.a);
}
var obj = {
a: 2,
foo: foo
};
var a = 'oops! global';
// CALLS `foo`, setting `this` during the call to `obj`.
// Result: Outputs "call1, 2" to the console.
var foocall = foo.call(obj, "call1");
// Since `foo` doesn't return anything, `foocall` is `undefined`
snippet.log("foocall's value: " + foocall);
// Calls `foo`, just like we did earlier
// Result: Outputs "call2, 2" to the console.
foo.call(obj, "call2");
// DOES NOT call `foo`. Just creates a new function that,
// when called, will call `foo` with `this` set to `obj`.
var foobind = foo.bind(obj, "bound");
// Calls the bound version of `foo` after 100ms
// Result: "bound, 2" 100ms later
setTimeout(foobind, 100);
// Calls `foo` after 100ms. Since we're in loose mode,
// `foo` will get called with `this` set to the global object.
// Result: "undefined, oops! global" because we haven't passed
// a value for the `label` argument, and `this` is the global object
setTimeout(foo, 100);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>