如何在类构造函数中使用原型方法
问题描述:
我在这里阅读了关于为Javascript类定义方法Advantages of using prototype, vs defining methods straight in the constructor?,我选择了原型方法。但我遇到了一个问题,例如:如何在类构造函数中使用原型方法
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");
}
我该如何在构造函数中调用原型函数?我尝试了原型方法的前向声明,但我认为问题在于我称之为this.Hide()没有帮助!
感谢您的时间!
答
您在使用错误的this
。您用来拨打Hide()
的this
实际上是#button
元素。分配this
那就是MyClass
对象到一个局部变量,然后使用在点击委托:
...
this.layout.append(this.button);
var $this = this;
$("#button1").click(function() {
$this.Hide();
});
...
答
你没有调用构造函数Hide
。你在click
回调中调用它,它具有不同的上下文(this
是不同的)。
使用临时变量到参考存储对当前的对象:
var t;
t = this;
...click(function() {
t.hide();
});
此外,JavaScript的约定是PascalCase
用于构造函数和camelCase
用于功能/方法。
答
$("#button1").click(function() {
//How can I call hide
this.Hide()//Error
});
在这行代码中,this
引用按钮(它在函数内部)。 之前的部份结合,可以定义var that = this;
,并在回调使用that
:
function MyClass() {};
MyClass.prototype.Hide = function() {};
function MyClass() {
var that = this;
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
that.Hide();
});
}
MyClass.prototype.Hide = function() {
this.layout.hide("slow");
}
答
您可以从构造函数中调用原型方法。你的问题是你正在放弃匿名点击功能的上下文。所以你有两种选择:
// 1. link to original object
var self = this;
$("#button1").click(function() {
self.Hide();
});
// 2. use proxy (bind) to invoke method in correct context
// there is built in function available in jQuery
$("#button1").click($.proxy(function() {
this.Hide();
}, this));
你有第二个解决方案是幻想,但我认为我们都可以同意第一个更容易阅读。 – 2011-12-16 15:11:45