我一直在学习 JavaScript 的课程, 使用原型, 最后如何继承。
根据我的理解,以下内容应:
- Alert "John" due to
myInstance.getIt();
being called - Alert "Jack" due to
myInheritedInstance.getIt();
being called myInheritedInstance.getParent();
has been assigned to.getIt()
in MyClass- This should then alert "John" when myInheritedInstance.getParent(); is called.
相反,实际发生的情况是:
- Alert "John"
- Alert Blank
- Alert "Jack"
我有一种感觉,我做了一些蠢事 或者误解了一个基本概念, 所以,如果有任何帮助,都会感激不尽。
var MyClass = function() { };
MyClass.prototype.constructor = MyClass;
MyClass.prototype.name = "John";
MyClass.prototype.getIt = function () { alert(this.name); };
var myInstance = new MyClass();
myInstance.getIt();
//Now inheritance
var MyInheritedClass = function () { };
MyInheritedClass.prototype = new MyClass;
MyInheritedClass.prototype.constructor = MyInheritedClass;
MyInheritedClass.prototype.name = "Jack";
MyInheritedClass.prototype.getIt = function () { alert(this.name); };
MyInheritedClass.prototype.getItParent = MyClass.prototype.getIt.call(this);
var myInheritedInstance = new MyInheritedClass();
myInheritedInstance.getIt();
myInheritedInstance.getItParent();