JavaScript OOP三种实现继承的方式(回顾)

1.Prototype形式

假设有那么一个类Person

function Person(name,sex){

    this.name = name

    this.sex = sex

}

Person.Protype.ablity = function(){

    alert(“my name is ”+name)

}

又有那么一个类,继承上面的Person的方法

function Student(){

    this.grade = 4

}

Student.prototype = new Person(“xzh”,”male”)//在这里传参

var std = new Student()

    std.ablity()//输出my name is xzh


2.call方法实现

父类也是上面那个

子类可以这样

function Student(name,sex){

  this.grade = 4

    Person.call(this,name,sex)

}

var stu = new Student(“xzh”,”male”)

    stu.ablity();//输出同样的结果


3.apply,跟call差不多一个鸟样,只不过用的是参数列表形式传参

function Student (){

    this.grade = 4

    Person.apply(this,arguments)

}


var stu = new Student(“xzh”,”male”)

    stu.ablity()//输出的结果一个几把样

你可能感兴趣的:(JavaScript OOP三种实现继承的方式(回顾))