2014-01-06 59 views
0

當用戶點擊一個從我的Class中調用Function的按鈕時,我需要調用一些私有變量。Javascript:從「private Method」調用「pubilc Variable」

這裏是我的代碼: -

class01 = new MyClass('Tom Marvolo Riddle'); 

function MyClass(name){ 

    this.name = name; 

    var draw = function(){ 
     var newHTML ='<input type="button" value="hello" />'; 
     $(".ctn").append(function(){ 
      return $(newHTML).click(hello); 
     }); 
    } 

    var hello = function(){ 
     alert ('hello, my name is '+this.name+'.') 
    } 

    draw(); 

} 
+4

您通過引入新的範圍丟失的上下文。緩存'this'例如:'var self = this'然後使用'self'。 – elclanrs

+3

或者,嘗試'var hello = function(){alert('hello,我的名字是'+ this.name +'。'); } .bind(this);' - bind保持上下文。 –

+0

@BenjaminGruenbaum發表回覆? –

回答

1

hello功能,被調用時,this指按鈕點擊,這不會有我們存儲name屬性。所以,我們捕捉當前對象而分配name,另一個變量,這樣

function MyClass(name){ 

    var that = this; 
    that.name = name; 

    ... 
    var hello = function(){ 
     console.log ('hello, my name is ' + that.name + '.'); 
    } 
    draw(); 
} 

var class01 = new MyClass('Tom Marvolo Riddle'); 
相關問題