0

프로토 타입은 상속 된 객체입니까? 다음 예제에서 자식처럼 모든 객체 인스턴스에 의해.Javascript : 프로토 타입 개체의 새 인스턴스를 만드는 방법은 무엇입니까?

부모의 인스턴스 여야합니다. 그렇지 않으면 부모의 프로토 타입이 상속되지 않습니다.

이 경우 목표는 하위의 각 인스턴스에 대해 parent에서 상속 된 별도의 배열을 만드는 것입니다.

정확히 어떻게 달성 할 수 있을지 확신하지 못합니다. 나는 extend을 안다.

확장 메서드는 단순히 프로토 타입을 새 개체로 복사하고 새 메서드를 적용하는 것입니까?

내 코드 예제 + jsfiddle :

function parent(){ 
} 

parent.prototype.arr = []; 
parent.prototype.add = function(item){ 
    this.arr.push(item); 
} 
parent.prototype.show = function(){ 

    for(var i = 0; i < this.arr.length; ++i){ 
     $('body').append(this.arr[i]); 
    } 
} 


function child(childname){ 
    this.add(childname); 
} 
child.prototype = new parent(); 


var child1 = new child('child1'); 
var child2 = new child('child2'); 

child2.show();//this should only show child2? 
+0

http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks

+1

'parent.prototype.arr = [:

좋은 설명이 MDN 문서를 참조하십시오 ]; '이것은 항상 잘못이다; 당신은 하나의 인스턴스 만 가질 수 있습니다. – SLaks

+0

'child.prototype = new parent();'는 아무 것도 유용하지 않습니다. Object의 public * prototype * 속성을 만드는 것은 상속받은 private ['[[Prototype]]] (http://ecma-international.org/ecma-262/5.1/#sec-8.6.2)와 완전히 다릅니다. 생성자로부터. – RobG

답변

0

는 각 인스턴스에게 자신의 배열을 제공하기 위해이 모든 인스턴스가 공유되기 때문에 배열을 유지하기 위해 프로토 타입을 사용하지 마십시오. 당신은 부모의 생성자에서 새로운 배열을 초기화 한 후 자식 클래스는 부모의 생성자를 호출해야합니다 수 있습니다 : 이제 모든 부모 개체가 일부 사람을 포함하여 배열의 복사본이있을 것이다

function parent(){ 
    this.arr = []; 
} 

function child() { 
    parent.call(this); // call parent constructor 
} 
child.prototype = Object.create(parent.prototype); 
child.prototype.constructor = child; 

을 자식 자손의 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

관련 문제