继承

69 阅读1分钟

父类

function Father(name) {
  this.name= name
  this.sleep = function() {
    console.log(this.name + ' is sleep ');
  }
}

Father.prototype.look = function(book) {
  console.log(this.name + ' is look ' + book);
}
  1. 原型继承
// 原型链继承
function Son() {}
Son.prototype = new Father()
Son.prototype.constructor = Son // 避免指向Father

var son1 = new Son()
console.log(son1.name);  // undefined
console.log(son1.sleep()); // undefined is sleep
console.log(son1.look('一千零一夜')); // undefined is look ...
// 子类不能调用父类传参
  1. Call
function Son(name) {
   Father.call(this)
   this.name = name
}
var son1 = new Son('zooey')
// 有name && sleep
// 没有 look  没有原型上的方法
  1. 组合
function Son(name) {
  Father.call(this)
  this.name = name
}
Son.prototype = new Father()
Son.prototype.constructor = Son
var son1 = new Son(‘mike’)
console.log(son1.name);
console.log(son1.sleep());
console.log(son1.look(“童话”));
// father 构造函数会执行两遍  Father.call  && new Father()
// Father.call 会覆盖new Father()
  1. 寄生组合
function Son(name) {
  Father.call(this)
  this.name = name
}
function createObj(obj) {
  var f = function(){}
  f.prototype = obj
  return new f()
}
Son.prototype = createObj(Father.prototype)
Son.prototype.contructor = Son
var son1 = new Son('luyis')
console.log(son1.name);
console.log(son1.sleep());
console.log(son1.look('百年'));