gpt4 book ai didi

javascript - 将函数复制到局部变量并保留 this 指针

转载 作者:行者123 更新时间:2023-11-28 18:50:47 27 4
gpt4 key购买 nike

我在原型(prototype)上有一个这样的函数:

Car.prototype.drive = function() {
this.currentSpeed = this.speed;
}

我想在另一个函数中经常调用这个函数,该函数也是原型(prototype) Car 的一部分。而且因为我很懒,所以我不想一直重写 this 。所以我想将对函数的引用复制到局部变量:

Car.prototype.doSomeThing = function() {
var driveReference = this.drive;
driveReference();
}

但是当我调用driveReference()时,driveReference()this指针指向Window 而不是我的 Car 实例。

有办法阻止这种情况发生吗?(apply() 可以工作,但这比使用 this 更冗长)

最佳答案

您可以使用Function.prototype.bind将函数的上下文绑定(bind)到您喜欢的任何内容:

Car.prototype.doSomeThing = function() {
var driveReference = this.drive.bind(this);
driveReference();
}

关于javascript - 将函数复制到局部变量并保留 this 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34495734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com