扫码关注官方订阅号
Document
这么改:
<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
this.sayHello
setTimeout
this
bind
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); };
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
这么改:
因为当你把
this.sayHello传给setTimeout后,this指针变了,所以需要用bind强制绑定到当前的thisES6写法