【发布时间】:2015-06-19 21:38:48
【问题描述】:
到目前为止,在创建需要访问其父级的函数之前,我一直使用var self = this。然而,bind() 方法似乎是一种更合适的方法,我正在探索该选项以及apply() 和call() 方法。
这是我用来比较所有三个的:
(function(){
this.say = function(text){
console.log(text);
}
this.run = function(){
console.clear();
setTimeout(function(){
this.say('bind');
}.bind(this), 1000);
setTimeout(function(){
this.say('call');
}.call(this), 1000);
setTimeout(function(){
this.say('apply');
}.apply(this), 1000);
}
this.run();
})();
但是脚本给我留下了一些问题:
为什么
call()和apply()方法不像bind()方法那样尊重超时,我应该使用哪一个?-
以下行为相似的语法之间是否有任何区别:
setTimeout( function(){ this.say('bind'); }.bind(this) , 1000); setTimeout( (function(){ this.say('bind'); }).bind(this) , 1000); setTimeout( (function(){ this.say('bind'); }.bind(this)) , 1000);
【问题讨论】:
-
.call和.apply的工作方式与.bind的工作方式不同。他们立即调用该函数。 -
同意@JesseKernaghan。
call和apply调用函数,而bind只绑定上下文。
标签: javascript closures this settimeout iife