function Parent(){ this.name = ‘kevin‘ } Parent.prototype.getName = function(){ console.log(this.name) } function Child(){ } Child.prototype = new Parent() var child = new Child() console.log(child.name) //kevin
优点:
缺点:
function Parent(name){ this.name = name } function Child(name){ Parent.call(this,name) } let child = new Child(‘Tom‘) let child1 = new Child(‘Jack‘) console.log(child.name) //Tom console.log(child1.name) //Jack
优点:
缺点:
function Parent(name){ this.name = name this.color = [‘red‘,‘bule‘,‘green‘] } Parent.prototype.getName = function(){ console.log(this,name) } function Child(name,age){ this.age = age Parent.call(this,name) } Child.prototype = new Parent() Child.prototype.constructor = Child Child.prototype.getAge = function(){ console.log(this.age) } let child = new Child(‘Tom‘,12) console.log(child.name) //Tom child.getAge() //12 child.color.push(‘blcak‘) console.log(child.color) //[‘red‘,‘bule‘,‘green‘,‘black‘] let child1 = new Child(‘Jack‘,18) console.log(child1.name) //Jack child1.getAge() //18 console.log(child1.color) //[‘red‘,‘bule‘,‘green‘]
优点:
缺点(小瑕疵):
function object(o){ function F(){} F.prototype = o return new F() } //在ES5中有了新方法代替Object.created(o,{name:‘Ton‘等新属性}) let person = { name:‘Tom‘, color : [‘red‘,‘bule‘,‘green‘] } let person1 = Object.create(person) let person2 = Object.create(person) person1.name = ‘Jack‘ person1.color.push(‘black‘) person2.name = ‘Kevin‘ person1.color.push(‘yellow‘) console.log(person1.name) //Jack console.log(person2.name) //Kevin console.log(person1.color == person2.color) //true
优点:
缺点:
let person = { name:‘Tom‘, color : [‘red‘,‘bule‘,‘green‘] } function createAnother(o){ let clone = create(o) clone.getName(){ console.log(this.name) } return clone //clone这个对象不仅有原型引用属性,还有自己的方法 } let person1 = createAnother(person) person1.getName() //Tom
优点:
缺点:
##寄生组合式继承(最佳方式)
function Parent (name) { this.name = name; this.colors = [‘red‘, ‘blue‘, ‘green‘]; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } function prototype(Child,Parent){ //获得父类型原型上的方法 let prototype = object(Parent.prototype) //创建父类型原型的一个副本,相当于prototype.__proto__ = Parent.prototype prototype.constructor = Child Child.prototype = prototype } prototype(Child,Parent) //必须执行这个函数,才能进行给子类型原型写方法,顺序调转的话子类型原型会被重写 Child.prototype.getName = function(){ console.log(this.name) }
优点:完美 缺点:用起来麻烦
class Parent { constructor(name,age){ this.name = name this.age = age } showName(){ console.log(this.name); } } class Child extends Parent{ constructor(name,age,sex){ super(name,age) this.sex = sex } showSex(){ console.log(this.sex); } } let parent = new Parent(‘Jack‘,30) console.log(parent.name,parent.age); let child = new Child(‘Tom‘,12,‘男‘) console.log(child.name,child.age); child.showName() //Tom child.showSex() //男
原文:https://www.cnblogs.com/Gzzzh/p/10526149.html