【发布时间】:2016-12-31 05:26:05
【问题描述】:
我以为我对如何在 JavaScript 中正确扩展类有很好的理解,但是在扩展子类时,当我覆盖一个方法并从子类调用父方法时,我遇到了一个无限循环。我要么做错了,要么你不应该在 JavaScript 中这样子类化。
有人可以帮我介绍一下吗?
var Grand = function() {
this.test();
};
Grand.prototype.constructor = Grand;
Grand.prototype.test = function() {
console.log( "Grand!")
};
var Parent = function() {
this.supr.constructor.call( this );
};
Parent.prototype = Object.create( Grand.prototype );
Parent.prototype.constructor = Parent;
Parent.prototype.supr = Grand.prototype;
Parent.prototype.test = function() {
this.supr.test.call( this );
console.log( "Parent!" );
};
var Child = function() {
this.supr.constructor.call( this );
};
Child.prototype = Object.create( Parent.prototype );
Child.prototype.constructor = Child;
Child.prototype.supr = Parent.prototype;
Child.prototype.test = function() {
this.supr.test.call( this );
console.log( "Child!" );
};
var g = new Grand(); // Outputs "Grand!"
var p = new Parent(); // Outputs "Grand!" "Parent!"
var c = new Child(); // Error: Endless Loop!
我希望控制台记录“Grand!”、“Parent!”、“Child!”当实例化一个新的 Child() 时,我得到了一个无限循环。
我来自 ActionScript 背景,因此在 JavaScript 中创建类仍然会让我感到很困惑。提前感谢您的帮助!
【问题讨论】:
-
在 JavaScript 中并没有真正的类和子类的概念(除了 ES6 中的糖语法)。 JavaScript 是原型基础。
标签: javascript class inheritance