2011-12-16 70 views
0

我在這裏閱讀了關於爲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()沒有幫助!
感謝您的時間!

回答

2

您在使用錯誤的this。您用來撥打Hide()this實際上是#button元素。分配this那就是MyClass對象到一個局部變量,然後使用在點擊委託:

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

你沒有調用構造函數Hide。你在click回調中調用它,它具有不同的上下文(this是不同的)。

使用臨時變量到參考存儲對當前的對象:

var t; 
t = this; 

...click(function() { 
    t.hide(); 
}); 

此外,JavaScript的約定是PascalCase用於構造函數和camelCase用於功能/方法。

2
$("#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"); 
} 
0

您可以從構造函數中調用原型方法。你的問題是你正在放棄匿名點擊功能的上下文。所以你有兩種選擇:

// 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)); 
+0

你有第二個解決方案是幻想,但我認爲我們都可以同意第一個更容易閱讀。 – 2011-12-16 15:11:45

相關問題