<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
foo = function(){
this.myName = "Foo function.";
}
foo.prototype.sayHello = function(){
alert(this.myName);
}
foo.prototype.bar = function(){
setTimeout(this.sayHello, 300);
}
var f = new foo;
f.bar();
</script>
</body>
</html>
这么改:
<script>
var foo = function(){
this.myName = "Foo function.";
};
foo.prototype.sayHello = function(){
alert(this.myName);
}
foo.prototype.bar = function(){
setTimeout(this.sayHello.bind(this), 300);
}
var f = new foo;
f.bar();
</script>
因为当你把this.sayHello
传给setTimeout
后,this
指针变了,所以需要用bind
强制绑定到当前的this
foo.prototype.bar = function(){
setTimeout(function(){this.sayHello.bind(this)}, 300);
}
foo.prototype.bar = function(){
var _this = this;
setTimeout(function(){
_this.sayHello();
}, 300);
}
ES6写法
foo.prototype.bar = function(){
setTimeout(() => this.sayHello(), 300);
};