私はこのサイトでこのアイデアを最初に見つけました:
http://theburningmonk.com/2011/01/javascript-dynamically-generating-accessor-and-mutation-methods/
ポイントは、ローカル変数をクラス スコープに割り当てて、動的なクラス プロパティを設定することです。
このコードでは、ローカル変数 _this をクラス スコープに設定しています。しかし、何らかの理由で、_this のプロパティはクラスの外からアクセスできます。どうしてこれなの?_this は、作成時にプライベート メンバーとして宣言されます。
var MyClass = function( arg )
{
var _this = this;
_this.arg = arg;
// Creates accessor/mutator methods for each private field assigned to _this.
for (var prop in _this)
{
// Camelcases methods.
var camel = prop.charAt(0).toUpperCase() + prop.slice(1);
// Accessor
_this["get" + camel] = function() {return _this[prop];};
// Mutator
_this["set" + camel] = function ( newValue ) {_this[prop] = newValue;};
}
};
var obj = new MyClass("value");
alert(obj.getArg());
これはどうして走るのでしょうか?「値」を警告します。_this は非公開で宣言されているため、これにはアクセスできません。これを書いたとき、ミューテーター/アクセサーの割り当てが間違っていました。またはそう私はしかし。
これらのメソッドをクラススコープに割り当てて、これを書くつもりでした:
// Accessor
this["get" + camel] = function() {return _this[prop];};
// Mutator
this["set" + camel] = function ( newValue ) {_this[prop] = newValue;};
しかし、どちらも機能します。_this のプライベート メソッドが利用できるのはなぜですか?
どんな助けでも素晴らしいでしょう!
ありがとう、混乱したスクリプター