对象的继承

Posted woniubushinide

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象的继承相关的知识,希望对你有一定的参考价值。

一、原型继承 

  缺点:1、不能给父级构造函数传参

     2、父级构造函数中引用类型的数据,会被自己构造函数实例共享

  ps:这是下面实例中的2只猫,是不是萌萌哒!

      技术图片 这是小7         技术图片这是8哥

 

function Animal(name,age) 
  this.name = name
  this.age = age
  this.hobby = [‘music‘,‘dance‘]


Animal.prototype.say = function() 
  return this.hobby

function Cat(color) 
  this.color = color

Cat.prototype = new Animal(‘八哥‘,‘1‘)

var cat1 = new Cat(‘白色‘)
cat1.hobby.push(‘sleep‘)
var cat2 = new Cat(‘花色‘)

console.log(111,cat1.say()) //["music", "dance", "sleep"]
console.log(2222,cat2.say()) //["music", "dance", "sleep"]
console.log(333,cat1.name) //八哥
console.log(444,cat1.age) //1
console.log(555,cat1.color) //白色

二、借用构造函数继承

  缺点:无法继承原型中的方法

function Animal(name) 
  this.name = name
  this.hobby = [‘music‘,‘dance‘]


Animal.prototype.say = function() 
  return this.hobby

function Cat(color,name) 
  this.color = color
  Animal.call(this,name)


var cat1 = new Cat(‘白色‘,‘8哥‘)
cat1.hobby.push(‘sleep‘)
var cat2 = new Cat(‘花色‘,‘小七‘)

//console.log(111,cat1.say()) //报错 cat1.say is not a function
console.log(333,cat1.name) //八哥
console.log(444,cat1.color) //白色
console.log(555,cat2.name) //小七
console.log(666,cat2.color) //花色

三、组合继承

  完美的解决了前面2种方式造成的缺陷,但是我们会发现构造函数的属性会有冗余

function Animal(name) 
  this.name = name
  this.hobby = [‘music‘,‘dance‘]


Animal.prototype.say = function() 
  return this.hobby


function Cat(color,name) 
  this.color = color
  Animal.call(this,name)


Cat.prototype = new Animal(‘66‘)

var cat1 = new Cat(‘白色‘,‘8哥‘)
cat1.hobby.push(‘sleep‘)
var cat2 = new Cat(‘花色‘,‘小七‘)

console.log(111,cat1.say()) //["music", "dance", "sleep"]
console.log(222,cat2.say()) //["music", "dance"]
console.log(333,cat1.name) //八哥
console.log(444,cat1.color) //白色
console.log(555,cat2.name) //小七
console.log(666,cat2.color) //花色

四、升级一下

function Animal(name)
this.name = name
this.hobby = [‘music‘,‘dance‘]

Animal.prototype.say = function()
return this.hobby

function Cat(color,name)
this.color = color
Animal.call(this,name)

Cat.prototype = Animal.prototype

var cat1 = new Cat(‘白色‘,‘8哥‘)

console.log(111,cat1 instanceof Cat)//true
console.log(222,cat1 instanceof Animal)//true
console.log(333,cat1.constructor)//Animal
 
我们会发现,判断实例的构造函数打印出来的跟我们预期不符
 
优化
function Animal(name)
this.name = name
this.hobby = [‘music‘,‘dance‘]

Animal.prototype.say = function()
return this.hobby

function Cat(color,name)
this.color = color
Animal.call(this,name)

Cat.prototype = Object.create(Animal.prototype) 
Cat.prototype.constructor = Cat
var cat1 = new Cat(‘白色‘,‘8哥‘)

console.log(111,cat1 instanceof Cat)//true
console.log(222,cat1 instanceof Animal)//true
console.log(333,cat1.constructor)//Cat

以上是关于对象的继承的主要内容,如果未能解决你的问题,请参考以下文章

面向对象。对象的继承

javascript:对象的继承

JavaScript教程——对象的继承

Java面向对象之继承

JS面向对象---继承

js里面的对象继承几种方法