js apply 和call的区别

时间:2023-03-09 15:57:52
js apply 和call的区别

function Person(name, profession) {
  this.name = name;
  this.profession = profession;
  this.speak = function () {
    document.writeln("我叫"+name+",我是一位"+profession);
  }
}

function Student(name,profession) {
  Person.call(this,name,profession);
};

function Teacher(name, profession)
{
  Person.apply(this, arguments);
}

var student = new Student("张三", "学生");
var teacher = new Teacher("李四", "老师");

student.speak();
teacher.speak();

结果如下

js apply 和call的区别

从结果中我们可以看到,apply和call可以实现继承,但call的用法要比apply灵活