저는 자바 스크립트 기술을 새로 고쳐서 객체가 다른 것으로부터 상속받을 수있는 방법을 생각해 냈습니다. 상속은 나무와 비슷해야합니다.javascript multilevel inheritance 이상한 결과
Parent->Child->Child2
나는 확장 한 Function.prototype
(이,이 나중에 변경 될 수 있습니다 나쁜 생각 말하지 마)
Function.prototype.extend = function(child)
{
// save child prototype
var childPrototype = child.prototype;
// copy parent to child prototype
child.prototype = Object.create(this.prototype);
// merge child prototype
for (var property in childPrototype) {
child.prototype[property] = childPrototype[property];
}
child.prototype.constructor = child;
child.prototype.$parent = this.prototype;
return child;
};
부모 개체 :
var Parent = (function()
{
var Parent = function(x, y)
{
this.x = x;
this.y = y;
console.log('Parent constr', x, y);
}
Parent.prototype.move = function(x, y)
{
this.x += x;
this.y += y;
console.log('Parent moved.');
};
return Parent;
}());
첫 번째 아이 :
var Child = Parent.extend(function()
{
var Child = function(x, y)
{
this.$parent.constructor(x, y);
console.log('Child constr');
}
Child.prototype.print = function()
{
console.log('Child print', this.x, this.y);
};
// override
Child.prototype.move = function(x, y)
{
this.$parent.move(x, y);
console.log('Child moved.');
};
return Child;
}());
둘째 아이 :
var Child2 = Child.extend(function()
{
var Child2 = function(x, y)
{
this.$parent.constructor(x, y);
console.log('Child2 constr');
}
// override
Child2.prototype.move = function(x, y)
{
this.$parent.move(x, y); // call parent move
console.log('Child2 moved.');
};
return Child2;
}());
지금까지 너무 좋아. 부모 생성자와 메서드를 호출하고 메서드를 재정의 할 수도 있습니다.
var child = new Child2(1, 1);
child.move(1, 1);
child.print();
내가 올바른 출력 다음 얻을 :
Parent constr 1 1
Child constr
Child2 constr
Parent moved.
Child moved.
Child2 moved.
Child print 2 2
을하지만 둘째 아이의 재정을 주석 만약 내가 다음 얻을 출력 :
Parent constr 1 1
Child constr
Child2 constr
Parent moved.
Child moved.
Child moved. -> WHY??
Child print 2 2
나는 이유를 이해하지 않습니다 Child moved.
이 두 번 출력됩니다. 결과는 정확하지만 이상한 일이 일어나고 있습니다.
편집 :
마지막으로 더 나는 좋은 솔루션과 함께 제공되는 문제로 연구하고 다이빙 후 : 내가 다른 확장했다
// call method from parent object
Object.getPrototypeOf(Child2.prototype).move.apply(this, arguments);
Function
에 : 다음
Function.prototype.getParent = function()
{
return Object.getPrototypeOf(this.prototype);
};
그리고에 대한 예 : Child2
이동 방법 :
Child2.prototype.move = function(x, y)
{
Child2.getParent().move.call(this, x, y);
};
그래서 더 이상 $parent
이 필요 없으며 원하는 결과를 얻습니다.
또 다른 해결책은 바로 부모의 프로토 타입을 호출하는 것입니다 :
는Child2.prototype.move = function(x, y)
{
Child.prototype.move.call(this, x, y);
};
다중 레벨 상속은 다중이 아닙니다. – C5H8NNaO4
감사합니다. 제목을 편집했습니다. – bitWorking
정확히 어떤 부분을 "주석 처리 해제 하시겠습니까?" 내가 주석으로 처리 된 코드는 없다. – apsillers