10

私はプロトタイピングとインスタンス化が初めてなので、質問がありました:

  • デフォルトの配列関数を変更せずに、プロトタイプでいくつかのプロパティが追加された新しい配列を構築する関数を作成するにはどうすればよいですか?

例えば ​​:

function Cool_Object() {
    this = new Array() // Construct new array.
    //This is only for the example. I know you can't do that.
}
Cool_Object.prototype.my_method = function() {
    // Some method added
};

したがって、次のように呼び出すと:

var myObject = new Cool_Object();

myObject は配列であり、" my_method" というメソッド (実際には関数を呼び出します) を持ちます。

ただし、デフォルトの Array オブジェクトはそのままです。

前もって感謝します !

4

5 に答える 5

10

あなたはそれを少し後ろに持っています。Array.prototypeカスタムオブジェクトのプロトタイプとして使用してください。

function Cool_Object() {

    this.my_method = function () {
        return 42;
    }
}

Cool_Object.prototype = Array.prototype;

var foo = new Cool_Object();
foo.my_method(); // 42
foo.push(13);
foo[0]; // 13

中間型を導入することで、 を変更せずにArray.prototypeとの両方のプロトタイプを取得できます。my_methodCool_ObjectArray.prototype

function Even_Cooler() {}
Even_Cooler.prototype = Array.prototype;

function Cool_Object() {}
Cool_Object.prototype = new Even_Cooler();

Cool_Object.prototype.my_method = function () {
    return 42;
}
于 2013-01-11T00:24:25.223 に答える
6

に代入することはできませthisん。機能せず、ReferenceError. Cool_Object拡張するだけArrayです。

それを行う1つの方法:

var Cool_Object = Object.create(Array.prototype);
Cool_Object.my_method = function() {
    // Some method added
};

次に、さらにオブジェクトを作成します

var obj = Object.create(Cool_Object);
于 2013-01-11T00:26:55.353 に答える
1

関数のプロトタイプとして配列を使用して、新しい型が Array から「継承」されるようにし、プロトタイプに新しいメソッドを導入します。

function CustomArray() {}

CustomArray.prototype = [];

// introduce a new method to your custom array type
CustomArray.prototype.total = function() {
    return this.reduce(function(ret, el) {
        return ret+el;
    }, 0);
};

// introduce another new method to your custom array type
CustomArray.prototype.arithmetiMean = function() {
    return this.total()/this.length;
};

または、これらのメソッドを新しいインスタンスに導入することもできます。

function CustomArray() {
    // introduce a new method to your custom array object
    this.total = function() {
        return this.reduce(function(ret, el) {
            return ret+el;
        }, 0);
    };

    // introduce another new method to your custom array object    
    this.arithmetiMean = function() {
        return this.total()/this.length;
    };
}

CustomArray.prototype = [];

var arr = new CustomArray();

arr.push(1); // push is an array-standard method
arr.push(2);
arr.push(3);
arr.push(4);
arr.push(5);
arr.push(6);
arr.push(7);
arr.push(8);
arr.push(9);
arr.push(10);

console.log(arr.arithmetiMean());
于 2013-01-11T00:30:16.503 に答える