2011-01-01 17 views
4

オブジェクトメソッド(同じオブジェクト)のプロパティ定義を無駄に呼び出そうとしています。オブジェクトプロパティ定義からオブジェクトメソッドを呼び出す

var objectName = { 
    method : function() { 
      return "boop"; 
    }, 
    property : this.method() 
}; 

この例では、objectName.method( "boop")の戻り値をobjectName.propertyに割り当てたいとします。

私はobjectName.method(),method(),window.objectName.method()と同様に、すべてのブラケット表記の変形を試しました。 this["method"]、運がない。

+0

を私はメソッドに 'プロパティ' を変更することができます:方法2:関数(){(this.method返します)。 }しかし、私は内容が動的ではないので避けたい。 – Ian

+0

現在のバージョンのJavaScriptには、ダイナミックプロパティのようなものはありません。 – PatrikAkerstrand

+0

私は、初期化後にプロパティの値を変更する必要がないことを意味しました。 – Ian

答えて

5

(まだ初期化されていない)プロパティmethodを保持するオブジェクトではなく海流コンテキストを参照していない - これは何のmethod性質を持っていないので、あなたはTypeError例外を取得します。

あなたが望む場合はカスタムgetterですが、gettersとsettersをjavascriptで使用すると、ES5以前のECMAscriptではサポートされていませんが、多くのエンジンsupport them nonethelessでサポートされています。これを行うための

-1

はあなただけ行かない:

var objectName = { 
    method : function() { return "boop"; }, 
    property : function() { return this.method(); } 
}; 
+0

コードでは、 "property"は関数であり、method()の戻り値ではありません。 –

1

私はこれをしたいと思うない理由を見ることはできませんか?

メソッド名を使用しない場合は、単にゲッターを使用するだけではどうでしょうか。初期this

var objectName = { 
    method : function() { 
     return "boop"; 
    }, 
    property : function() { 
     return this.method(); 
    } 
}; 
+0

私はそれが問題を解決しないと思います。 objectName.property()を関数として呼び出す必要がある場合は、objectName.propertyを使用して値自体を取得することはできません。 –

0
/* overwrites the `property` function with a the set value 
* the first time it's called. From then on it's just a 
* property 
*/ 
var objectName = { 
    method: function(){ return 'boo'; }, 
    property: function(){ 
     var returnValue = this.method(); 
     this.property = returnValue; 
     return returnValue; 
    } 
}; 

/* or */ 
var objectName = { 
    property: (function(){ return 'boo'; }()); 
}; 
/* this evaluates the anonymous function within 
* the parenthetical BEFORE the definition of 
* objectName leaving only the returned value 
* to be set to property 
*/ 

/* or */ 

var objectName = { 
    method: function(){ 
     this.property = 'boop'; 
     return this.property; 
    } 
} 
/* calling the method to create/set the property 
* for objectName to the evaluated value 
*/ 

/* or */ 

var objectName = { 
    data: { 
     property: 'boop' 
    }, 
    property: function(value){ 
     if (value) this.data.property = value; 
     return this.data.property; 
    } 
}; 

/* the last one, I believe, is a neat way of handling 
* both set and get stealing the concept from my use 
* with JQuery. 
* set = objectName.property('boo'); 
* get = objectName.property(); 
*/ 
+1

すべての例で、「プロパティ」は値そのものではなく関数です。 –

0

もう一つの方法:objectnameはすでに 'メソッド' を呼び出した時に初期化

var objectName = { 
    method : function() { 
     return "boop"; 
    } 
}; 

$.extend(objectName, { 
    property : objectName.method() 
}) 

0

次のようにそれは私の仕事:

var objectName = { 
    method : function() { 
      return "boop"; 
    }, 
    property : objectName.method() 
}; 
関連する問題