标签:缺陷 alt nbsp 不能 报错 music instance 类型 解决
一、原型继承
缺点: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) //花色
四、升级一下
标签:缺陷 alt nbsp 不能 报错 music instance 类型 解决
原文地址:https://www.cnblogs.com/woniubushinide/p/11270141.html