為什么我在給子類添加原型方法后無法調(diào)用父類原型上的方法
function Person(name, age) {
this.name = name || "person";
this.age = age || 0;
}
Person.prototype = {
LEG_NUM:2,
ARM_NUM:2,
sayHi: function () {
console.log("my name is" + this.name + "my age is " + this.age + "years old");
},
walking: function () {
console.log(this.name + "is walking");
}
}
function Student(name, age, classname) {
Person.call(this, name, age);
this.classname = classname;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype = {
sayHi: function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
},
learn: function (obj) {
console.log(this.name + "is learning..." + obj);
}
}
var leo = new Student("leo", 12, "class 2,grade 3");
leo.walking();
leo.sayHi();
leo.learn("math");
console.log(leo.LEG_NUM);
console.log(leo.ARM_NUM);
去掉子類的原型方法就能用了????
2018-10-10
剛看了書,樓上說的極是,不能使用對象字面量創(chuàng)建原型方法,這樣會(huì)重寫原型鏈。
2018-10-10
Student.prototype = {
sayHi: function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
},
learn: function (obj) {
console.log(this.name + "is learning..." + obj);
}
}
這一句不能這么寫,這樣等于把Student.prototype的值更改為后面所定義的對象,而不是父類的實(shí)例,包括你上面定義的constructor屬性的定義也會(huì)失效,應(yīng)該寫成:
Student.prototype.sayHi=function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
};
Student.prototype.learn=function (obj) {
console.log(this.name + "is learning..." + obj);
};
切記:不要用字面量寫法,因?yàn)樗鼤?huì)整個(gè)替換掉prototype所指向的對象