javascript继承

2020-01-14  本文已影响0人  leleo

原型链继承

// 父级构造函数
function Person(){
  this.name = '张三';
  this.pets = ['小桌子','小椅子'];
}
Person.prototype.run = function(){
  console.log('上课')
}

// 子集构造函数
function Student(){
  this.num = '2'
}

// 1. 构造父类的实例
var p = new Person();
// 2. 设置为子类的原型对象
Student.prototype = p;
// 3. 修改constructor指针即可
Student.prototype.constructor = Student;

var s = new Student();
console.log(s);

寄生式组合继承

// 父级构造函数
function Person(name,pets){
  this.name = name;
  this.pets = pets;
}
Person.prototype.run = function(){
  console.log('上课')
}

// 子集构造函数
function Student(num,name,pets){
  Person.call(this,name,pets);
  this.num = num;
}

// 寄生式继承
function Temp(){}
Temp.prototype = Person.prototype;
var t = new Temp();
Student.prototype = t;
t.constructor.name = Student;



var s1 = new Student('001','张三',['小猫','小狗']);
var s2 = new Student('002','李四',['小马','小李']);
console.log(s1)
console.log(s2)

上一篇下一篇

猜你喜欢

热点阅读