2011-12-30 14 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

関数を呼び出すときは、関数が呼び出されたオブジェクトを参照します。または、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(); 

同じことを書くもう1つの方法:

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

myObject.SayMyName(); 

機能を呼び出す方法はいくつかあります。

関連する問題