Sid*_*rth 6 javascript this settimeout
这里我从 MDN 复制了代码片段:https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom();
// after 1 second, triggers the 'declare' method
Run Code Online (Sandbox Code Playgroud)
最令人困惑的部分是: window.setTimeout(this.declare.bind(this), 1000);
我了解如何this工作并且this内部 settimeout 始终绑定到全局对象。我知道在bloom函数内部可以有var self或var。
该行中有两个this,但this指的是什么以及如何工作完全令人困惑。
如何运作?
首先阅读这篇文章,它提供了一个非常好的关于如何this工作的解释。
.bind(this, args)只是帮助你this在你的函数中传递你的上下文(因为在你的例子中默认情况下它this是undefined或指的是window)。
也是bind一个不错的选择:
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
var self = this;
window.setTimeout(self.declare, 1000);
};
Run Code Online (Sandbox Code Playgroud)
作为最后一点,es6你可以这样做:
window.setTimeout(() => {
//do some stuff
}, 1000);
Run Code Online (Sandbox Code Playgroud)
代替
window.setTimeout(function () {
//do some stuff
}.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)
这让你不用去想this。
MSDN 定义Function.prototype.bind()为,
bind() 方法创建一个新函数,该函数在调用时将其 this 关键字设置为提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。
通过使用.bind(this)我们传递this给函数declare
看到这个片段。
function LateBloomer() {
console.log(this.constructor);
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.undefinedbloom = function() {
window.setTimeout(this.declare, 1000);
};
LateBloomer.prototype.declare = function() {
console.log(this.constructor);
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom();
flower.undefinedbloom();Run Code Online (Sandbox Code Playgroud)
在函数中,undefinedbloom我们只是调用了declare 函数。所以对象将是window对象。它没有属性,petalCount因此未定义。
在函数中,bloom我们将thisof绑定LateBloomer到声明函数,通过它我们将可以访问LateBloomer's 对象petalCount。
this JavaScript 一开始是很难理解的。
MDN 链接:https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this
| 归档时间: |
|
| 查看次数: |
8985 次 |
| 最近记录: |