2011-12-30 116 views
0


內部的jQuery函數內的對象參數值我有這樣的:獲取對象的方法

function test1() 
{ 
    this.count = 0; 
    this.active = 0; 
    this.enable = function() {this.active = 1;} 
    this.disable = function() {this.active = 0;} 
    this.dodo = function() 
       { 
        $("html").mousemove(function(event) { 
         // I want to get here the "active" param value;     
        }); 
       } 
    this.enable(); 
    this.dodo(); 
} 

instance = new test1(); 
instance.disable(); 

比方說,我要檢查的TEST1類的活動PARAM在評論的地方。我怎樣才能在那裏? 謝謝!

回答

2

如果你想獲得更高的範圍內的所有成員變量,你只需要從範圍this指針保存到一個局部變量,所以你可以使用它的其他範圍內:

function test1() { 
    this.count = 0; 
    this.active = 0; 
    this.enable = function() {this.active = 1;} 
    this.disable = function() {this.active = 0;} 
    var self = this; 
    this.dodo = function() { 
     $("html").mousemove(function(event) { 
      // I want to get here the "active" param value;     
      alert(self.active); 
     }); 
    } 
    this.enable(); 
    this.dodo(); 
} 

instance = new test1(); 
instance.disable(); 
1
this.dodo = function() 
      { 
       var active = this.active; 

       $("html").mousemove(function(event) { 
        alert(active);    
       }); 
      } 
1

當你調用一個函數'this'引用該函數被調用的對象時,或者當你將它與關鍵字new一起使用時新創建的對象。例如:在JavaScript

var myObject = {}; 
myObject.Name = "Luis"; 
myObject.SayMyName = function() { 
    alert(this.Name); 
}; 

myObject.SayMyName(); 

注有多種方式來聲明,定義和分配領域和方法的對象,下面是寫了類似你寫相同的代碼:

function MyObject() { 
    this.Name = "Luis"; 
    this.SayMyName = function() { 
     alert(this.Name); 
    }; 
} 

var myObject = new MyObject(); 
myObject.SayMyName(); 

而另一種方式來寫同樣的事情:

var myObject = { 
    Name: "Luis", 
    SayMyName: function() { 
     alert(this.Name); 
    }, 
}; 

myObject.SayMyName(); 

也有幾種不同的方式來調用一個函數。

相關問題