为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在给子类添加原型方法后无法调用父类原型上的方法

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);


https://img1.sycdn.imooc.com//5bb598da00011d5904990177.jpg

去掉子类的原型方法就能用了????

正在回答

2 回答

刚看了书,楼上说的极是,不能使用对象字面量创建原型方法,这样会重写原型链。

0 回复 有任何疑惑可以回复我~

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的值更改为后面所定义的对象,而不是父类的实例,包括你上面定义的constructor属性的定义也会失效,应该写成:

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);

};

切记:不要用字面量写法,因为它会整个替换掉prototype所指向的对象



1 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么我在给子类添加原型方法后无法调用父类原型上的方法

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信