以下代码......
function ClassA() {
this.name = "ClassA";
this.sayParentName = function () {
console.log(this.name);
};
};
function ClassB() {
this.name = "ClassB";
sayName = function () {
console.log(this.name);
};
};
ClassB.prototype = new ClassA();
var test1 = new ClassB();
var test2 = new ClassB();
test1.sayParentName();
test2.sayParentName();
内存中只有sayParentName
个ClassA
的实例?或者是为创建的ClassB
的每个新对象创建的内存中的新实例(每个ClassB
都有自己的sayParentName
函数,它继承而不是仅使用单个sayParentName
父类)
如果创建了一个新实例,唯一的办法是将ClassA
的原型设置为函数(sayParentName
),例如在创建ClassA
对象之后
ClassA.prototype.sayParentName = function() { console.log( this.name) );