Javascript继承可以这样做吗?它有效,但它是正确的方式吗?

时间:2016-08-18 14:07:28

标签: javascript

这是父类

function Person(name,age)
{
    this.name = name;
    this.age =age;
    this.alertAge = function(){
        alert(age)
    };
    this.alertName = function(){
        alert(this.name)
    }
    this.setName = function(name){
        this.name = name;
    }
}

这是1级儿童课

function Student(name,age,id){
    this.id = id;
    Person.call(this,name,age);
}

这是2级儿童班

function IStudent(name,age,id,children)
{
    this.children = children;
    Student.call(this,name,age,id)
}

这是1级子对象

let s1 = new Student('Jacob',21,1001);
console.log(s1)

这是2级子对象

let s2 = new IStudent('Jonathan',28,1002,1);
console.log(s2)
s2.setName('Ramoji');
console.log(s2)

2 个答案:

答案 0 :(得分:0)

你忘记了原型链

您需要在代码中添加以下行:

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

IStudent.prototype = Object.create(Student.prototype);
IStudent.prototype.constructor = IStudent;

所以你可以像这样重写你的代码:

Person.prototype.alertAge = function() {
    alert(this.age);
}

答案 1 :(得分:0)

看这个链接: http://javascript.info/tutorial/inheritance 使用Prototype的类继承 https://www.youtube.com/watch?v=7oNWNlMrkpc

你可以看到书籍JavaScript Web Applications(O'Reilly) 或者用法语这本书:JavaScript_pour_le_Web_2.0