gpt4 book ai didi

javascript - 如何在类构造函数中使用原型(prototype)方法

转载 作者:行者123 更新时间:2023-11-28 13:54:58 26 4
gpt4 key购买 nike

我在这里阅读了有关为 Javascript 类定义方法的信息 Advantages of using prototype, vs defining methods straight in the constructor?我选择原型(prototype)方式。但我遇到一个问题,例如:

function MyClass() {};
MyClass.prototype.Hide = function() {};

function MyClass() {
this.layout = $("<div>", {id: "layout1"}).text("My content");
this.button = $("<input />", {id: "button1"});
this.layout.append(this.button);
$("#button1").click(function() {
//How can I call hide
this.Hide()//Error
});
}
MyClass.prototype.Hide = function() {
this.layout.hide("slow");
}

如何在构造函数中调用原型(prototype)函数?我已经尝试过原型(prototype)方法的前向声明,但我认为问题在于我调用它的方式,this.Hide()没有帮助!
感谢您的宝贵时间!

最佳答案

您使用了错误的this。您用来调用 Hide()this 实际上是 #button 元素。将作为 MyClass 对象的 this 分配给局部变量,然后在点击委托(delegate)中使用它:

...
this.layout.append(this.button);
var $this = this;
$("#button1").click(function() {
$this.Hide();
});
...

关于javascript - 如何在类构造函数中使用原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535884/

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