混合模式

function Person(name,age){
    this.name = name;
    this.age = age;
};
Person.prototype.printName = function(){
    console.log(this.name);
}
function Student(name,age){
    继承 Person 的属性
    Person.call(this,name,age);
}
function create(prototype){
    function F(){};
    F.prototype = prototype;
    return new F();
}

// 让Student的原型指向一个对象,该对象的原型指向了Person.prototype,通过这种方式继承 Person 的方法
Student.prototype = create(Person.prototype);
Student.prototype.printAge = function(){
    console.log(this.age);
}
var student = new Student('xin',22);
student.printName(); // "xin"

.

相关文章:

  • 2021-08-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-03-24
  • 2023-03-25
猜你喜欢
  • 2021-11-05
  • 2022-12-23
  • 2021-11-05
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案