JavaScriptプロトタイプ関数を使用して、「この」コンテキストで変数を初期化する

StackOverflow https://stackoverflow.com/questions/4759084

質問

私は言葉で説明するのが難しいと感じているので、ここに私が試しているコードのスニペットがありますが、Firefox/FirebugはTailspinに入ります!

私はフォローしようとしています これこれ ガイドとして。私がここでやろうとしているのはです

  1. new MyObject.Method( 'String'、OptionSArray);
  2. OptionArrayアイテムは、プロトタイプ機能セット()を使用して反復および保存されます

    if(typeof(MyObj) == 'undefined') MyObj= {};
        MyObj.Method = function initialise(id,options) 
    {
        this.id = id;
        this.options = options;
        this.properties ={};
    
        for (var i = 0; i < this.options.length; i++)  // =>options.length=2 (correct)
        {
            var obj = this.options[i];  
            //get the keynames, pass with values to Set() to update properties
            for (var keys in obj) 
            {
                console.log(keys);  //=> correctly prints 'property1' and 'currentValue'
                this.Set(keys,obj); //=> this is i guess where it enters a loop?
            }
        }
    }
    
    //sets properties
    MyObj.Method.prototype.Set = function (name, value) 
    {
        this.properties[name.toLowerCase()] = value;
    }
    

    そして、私のHTMLページスクリプトブロックには、

    window.onload = function () {
    
            var options = [
            {    property1: {
                    show: true,
                    min: 0,
                    max: 100
                }
            },
            {
                currentValue: {
                    show: true,
                    colour: 'black'
                }
            }
        ];
    
    var myObj = new MyObj.Method('someDivId',options);
    }
    

コードを複雑にしすぎている場合はアドバイスしてください。 HasownPropertyのチェックが役立つと思います。

役に立ちましたか?

解決

これは、あなたが望むものを達成するためのよりクリーンな方法でなければなりません:

function MyObj(id, options) { // a function that will get used as the constructor
    this.id = id;
    this.options = options;
    this.properties = {};
    this.set(options); // call the set method from the prototype
}

MyObj.prototype.set = function(options) { // set the options here
    for(var i = 0, l = options.length; i < l; i++) {
        var obj = this.options[i];
        for(var key in obj) {
            if (obj.hasOwnProperty(key)) { // this will exclude stuff that's on the prototype chain!
                this.properties[key] = obj[key];
            }
        }
    }
    return this; // return the object for chaining purposes
                 // so one can do FooObj.set([...]).set([...]);
};

var test = new MyObj('simeDivId', [...]); // create a new instance of MyObj
test.set('bla', [...]); // set some additional options

ノート: 何のために hasOwnProperty ご覧ください ここ.

他のヒント

私は宣言をしました MyObj 関数名を削除しました initialise あなたは明らかにこの機能をの特性であると宣言しているので MyObj. 。あなたの最終コードは以下のようになり、それは私のためにうまくいきます。あなたに注意してください できません 他のオブジェクトには、プロトタイプ関数を宣言するまで、実際に関数を呼び出します。 Set 働き。

var MyObj = {};

MyObj.Method = function (id,options)
{
    this.id = id;
    this.properties ={};

    for (var i = 0; i < options.length; i++)  // =>options.length=2 (correct)
    {
        var obj = options[i];  
        //get the keynames, pass with values to Set() to update properties
        for (var keys in obj) 
        {
            console.log(keys);  //=> correctly prints 'property1' and 'currentValue'
            this.Set(keys,obj); //=> this is i guess where it enters a loop?
        }
    }
}

MyObj.Method.prototype.Set = function (name, value) 
{
    this.properties[name.toLowerCase()] = value;
}

var options = [
    {    property1: {
            show: true,
            min: 0,
            max: 100
        }
    },
    {
        currentValue: {
            show: true,
            colour: 'black'
        }
    }
];

var myObj = new MyObj.Method('someDivId',options);
var MyObj = {};

MyObj.Method = function initialise(id,options) {

    this.id = id;
    this.options = options;
    this.properties = {};

    for (var i = 0; i < this.options.length; i++)
    {
        var obj = this.options[i];  
        for (var keys in obj) {

            this.Set(keys,obj[keys]); 

            //*fix obj => obj[keys] 
            // (and it should be singular key rather then keys

        }
    }

    console.log(this.properties) // will output what you want
}

//sets properties
MyObj.Method.prototype.Set = function (name, value) {
    this.properties[name.toLowerCase()] = value;
}


var options = [{
    property1: {
        show: true,
        min: 0,
        max: 100
    }
},{
    currentValue: {
        show: true,
        colour: 'black'
    }
}];

var myObj = new MyObj.Method('someDivId',options);

これはあなたがあなたを持っていたということです myobj = new myobj ... オンロードイベントとオプションの外側は、オンロードイベントにバインドされた匿名関数に対してプライベート変数として宣言されたため、その範囲外でした。

また、プロパティの名前を2倍にし、少し乱雑にしたため、値をプロパティにコピーしている方法も修正しました。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top