1. prototype chain to inherit
1 // 1. prototype inheritance chain 2 / * 3 disadvantages: all the attributes are shared, and can not pass parameters . 4 * / . 5 function the Person (name, Age) { . 6 the this .name = name . 7 the this .age = Age . 8 } . 9 = Person.prototype.sayName () => { 10 the console.log ( the this .name) . 11 } 12 is function Man (name) { 13 is 14 } 15 Man.prototype = new new the Person () 16 Man.prototype.name = 'zhangsan ' 17 var zhangsan = new Man ( 'zhangsan' ) 18 console.log (zhangsan.name) // zhangsan
2. The constructor inheritance (classical inheritance)
// constructor inheritance (classical inheritance) / * advantages: You can pass parameters Disadvantages: all methods in the constructor, create an object is created each time a corresponding method, greatly wasted memory * / function Perent (name, Age, Sex) { the this .name = name the this .age = Age the this .sex = Sex the this .sayName = function () { the console.log ( the this .name) } } function Child (name, Age, Sex) { Perent.call ( the this , name, Age, Sex) } the let Child = new new Child ( 'Lisi', 18 is, 'M' ) the console.log (Child) //Child { name: 'lisi', age: 18, sex: '男', sayName: [Function] }
3. The combination inheritance (+ constructor prototype chain)
// 3. The combined mode (prototype chain constructor +) / * This takes full advantage of the prototype chain constructor respective advantages, is the most commonly used JS inherited methods * / function Animal (name, Age) { the this . = name name the this .age = Age } Animal.prototype.sayName = function () { the console.log ( the this .name) } function Cat (name, Age, Color) { Animal.call ( the this , name, Age) the this . = Color Color } Cat.prototype = Animal.prototype // prototype prototype Cat Animal directed Cat.prototype.constructor = Cat //将Cat的构造函数指向Cat let cat = new Cat('xiaobai',3,'white') console.log(cat) //Cat { name: 'xiaobai', age: 3, color: 'white' } cat.sayName() //xiaobai
4.es6 methods inherited
// 4.es6继承方法 class Per { constructor(name){ this.name = name } sayName(){ console.log(this.name) } } class Son extends Per{ constructor(name,age){ super(name) this.age = age } } let son = new Son('zhangsan',18) console.log(son) //Son { name: 'zhangsan', age: 18 } son.sayName() //zhangsan