프로토 타입은 상속 된 객체입니까? 다음 예제에서 자식처럼 모든 객체 인스턴스에 의해.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?
http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks
'parent.prototype.arr = [:
좋은 설명이 MDN 문서를 참조하십시오 ]; '이것은 항상 잘못이다; 당신은 하나의 인스턴스 만 가질 수 있습니다. – SLaks
'child.prototype = new parent();'는 아무 것도 유용하지 않습니다. Object의 public * prototype * 속성을 만드는 것은 상속받은 private ['[[Prototype]]] (http://ecma-international.org/ecma-262/5.1/#sec-8.6.2)와 완전히 다릅니다. 생성자로부터. – RobG