2013-02-13 2 views
3

추가 메서드가있는 배열을 반환하고 싶습니다. 나는 보통 이런 일을 수행프로토 타입을 사용하여 메서드로 배열 만들기

MyConstructor = function(a, b, c){ 
    var result = [a, b, c]; 
    result.method1 = function(){ 
     return a + b + c ; 
    } 
    return result ; 
} 

var obj = MyConstructor(2, 4, 6); // removed `new` 

을하지만, 방법의 숫자로 성장 사용합니다, 내가 대신 새로운 (동일)를 정의하는 프로토 타입을 사용하는 것이 쉽게 유지하기 위해 (더 효율적으로)입니다 익명의 생각 함수는 매번 작동하지만 그 방법은 Array.prototype으로 끝나지 않으면이 작업을 수행 할 수있는 방법을 찾을 수 없습니다.

가능한가요? 그렇다면 어떻게해야합니까?

+0

1) 코드는 팩토리 메소드이며, 'new' 키워드는 무의미합니다. 2) # 1은 프로토 타입 체인을 무의미하게 사용합니다. – Shmiddty

+1

http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/ – Bergi

+0

감사합니다. 그러나 그것이 없어도 반환하는 객체의 원형에 메서드를 넣을 수는 없습니다. – ColBeseder

답변

2

한 가지 방법은 Shmiddty로 대답으로, 래퍼 개체를 사용하는 것입니다.

// Define some special methods for use 
var specialMethods = { 
    sum: function() { 
    var i = 0, len = this.length, result = 0; 
    for (i; i < len; i++) result += this[i]; 
    return result; 
    }, 
    average: function() { 
    return this.sum()/this.length; 
    } 
}; 

function specialize(array) { 
    var key; 
    for (key in specialMethods) { 
    if (specialMethods.hasOwnProperty(key)) { 
     array[key] = specialMethods[key]; 
    } 
    } 
    return array; 
} 

var arr = specialize([1, 2, 3, 4, 5]); 
console.log(arr.sum()); // 15 
console.log(arr.average()); // 3 

당신이 Array.prototype을 만지지 않는이 방법을 당신의 방법이 추가됩니다 : 당신이 래퍼를 사용하지만 직접 배열을 수정할하지 않으려면

또는, 당신은 단지 그것을 보완 할 수 배열을 반복해서 재정의 할 필요없이 배열에 추가 할 수 있습니다. 하지만 각 배열에 복사되기 때문에 메모리 오버 헤드가 발생합니다. 프로토 타입 조회는 수행하지 않습니다.

또한, 당신은 항상 그냥 배열에서 작동 기능을 정의 할 수 있다는 점에 유의하십시오

function sum(array) { 
    var i = 0, len = array.length, result = 0; 
    for (i; i < len; i++) result += array[i]; 
    return result; 
} 

당신은 somearray.sum()의 구문 설탕을 얻을하지 않습니다를하지만, sum 기능은 오직 한 번 정의된다.

모두가 당신이 원하는/원하는 것에 따라 다릅니다.

+0

구문 설탕은 운동의 요점입니다! 이 접근법은 내가 가진 것에 대한 좋은 개선입니다. Bergi는 위의 멋진 링크를 게시했지만 이러한 솔루션은 내 요구에 적합하지 않습니다. – ColBeseder

2

과 같을 것이다 프로토 타입 체인에 사용할 수 있도록하기 위해 예 수정 :

// this could still be var MyConstructor = function... 
// but I prefer this form for Classes 
function MyConstructor(a, b, c){ 
    this.result = [a, b, c]; 
} 

MyConstructor.prototype.method1 = function(){ 
    // Array.reduce can be used for summation, or you could hardcode something like: 
    // return this.result[0] + this.result[1] + this.result[2] 
    // or do a summation through a for-loop, etc 
    return this.result.reduce(function(a,b){return a+b}); 
} 

var obj = new MyConstructor(2, 4, 6); 
console.log(obj.result, obj.method1()); // [2, 4, 6] 12 
+0

하지만 이제 console.log (obj [0])가 표시되지 않습니다. – ColBeseder

관련 문제