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

来源:8-1 概念与继承

Elias丿纯黑

2018-10-04 12:37

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://img2.mukewang.com/5bb598da00011d5904990177.jpg

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

写回答 关注

2回答

  • web馒头
    2018-10-10 19:22:14

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

  • 慕粉0129131857
    2018-10-10 01:54:27

    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所指向的对象



JavaScript深入浅出

由浅入深学习JS语言特性,且解析JS常见误区,从入门到掌握

281112 学习 · 1020 问题

查看课程

相似问题