1. 繼承
-
簡介
一層原型鏈搜索不叫繼承,兩層原型鏈的搜索才叫繼承let a = new Array(); a.__proto__ === Array.prototype a.push() //這個方法是Array.prototype的,不是繼承 a.__proto__.__proto__ === Object.prototype a.valueOf() //這個方法是Object.prototype里的,是繼承
a.valueOf()這個方法就叫繼承的
實現(xiàn)
- ES5的繼承
這樣pyz.run就是繼承屬性,因為經(jīng)過了兩層原型鏈的搜索。function Human(name){ this.name = name; } Human.prototype.run = function(){ console.log("我叫" + this.name + "我在跑步") return } function Man(name){ Human.call(this,name); //引用Humnan的自身的屬性屬性 this.gender = '男' } Man.prototype.fight = function(){ console.log('打架') } Man.prototype.__proto__ = Human.prototype //將Man的原型的原型指向Human.prototype let pyz = new Man('pyz')
兼容IE,Man.prototype.__proto__ = Human.prototype
這句IE不支持,可以寫成下面這樣let f = function(){} f.prototype = Human.prototype Man.prototype = new f();
- ES6
class Human{ constructor(name){ this.name = name } run(){ console.log('我叫' + this.name + '我在跑步') return } } class Man extends Human{ //繼承Human的原型鏈 constructor(name){ super(name) //用它繼承的類里的name this.gender = '男' } fight(){} }
- ES5、ES6的優(yōu)劣
用ES6在原型聲明非函數(shù)的方法很奇怪。。。
ES5可以Human.prototype.race = '人類'