gpt4 book ai didi

javascript - 如何在同一个对象中调用原型(prototype)函数?

转载 作者:行者123 更新时间:2023-11-30 10:49:45 25 4
gpt4 key购买 nike

我有以下 javascript 代码。

var Test = function(){



$("#"+elementId).click(function(){
// How to call Test.callbackTest here?
});

}

Test.prototype.callbackTest = function(){
//code
}

如果我想在点击事件中调用callbackTest(),是否必须使用this.callbackTest()?

或者有什么更好的方法吗?

最佳答案

如果您想使用 from click function ,this.callbackTest() 将不起作用,因为它会绑定(bind)到 window 对象而不是您的函数。有多种方法可以做到这一点……一种快速的方法

    var Test = function(){

var that = this

$("#"+elementId).click(function(){
// How to call Test.callbackTest here?
that.callbackTest();
});

}

Test.prototype.callbackTest = function(){


//code
}

jquery 还提供了一个 proxy解决方案,我建议您检查一下。如果你使用它,你的代码会像

  var Test = function(){

$.proxy(this.callbackTest,this) // This ensures that wheneven callbackTest is called , 'this' inside callbackTest will be bound to current object , in this case Test
$("#"+elementId).click(function(){
//AND THEN YOU CAN USE THIS here
this.callbackTest();
});

}

Test.prototype.callbackTest = function(){


//code
}

关于javascript - 如何在同一个对象中调用原型(prototype)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6193411/

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