我在这样的原型上有一个功能:
Car.prototype.drive = function() {
this.currentSpeed = this.speed;
}我想经常在另一个函数中调用这个函数,它也是原型车的一部分。而且,由于我很懒,所以我不想一直重写this。因此,我想将对函数的引用复制到一个局部变量:
Car.prototype.doSomeThing = function() {
var driveReference = this.drive;
driveReference();
}但是,当我调用driveReference()时,this-pointer of driveReference()指向Window而不是指向Car实例。
有可能阻止这种情况吗?(apply()可以工作,但这比使用this更冗长)
发布于 2015-12-28 14:56:18
您可以使用Function.prototype.bind将函数的上下文绑定到任何您喜欢的内容:
Car.prototype.doSomeThing = function() {
var driveReference = this.drive.bind(this);
driveReference();
}发布于 2015-12-28 14:57:06
你可以写
var driveRef = this.drive.bind(this);但是可能会产生一些不必要的性能影响。。或者您只需将this复制到一个较短的变量名:
var me = this;
me.drive();显式地使用上下文对象的引用是JavaScript的一个非常基本的设计特性,因此很难绕过它。
https://stackoverflow.com/questions/34495734
复制相似问题