用於實現函數繼承,call的第二個參數能夠是任意類型es6
function Animal(){ this.name = ""; this.say = function(){ console.log("hello"); } } function dog(){ this.name = "xiao"; //把Animal的方法應用到dog這個對象身上 Animal.call(this); } console.log(new dog()); // dog { name: '', say: [Function] }
用於實現函數繼承,apply的第二個參數必須是數組,也能夠是arguments數組
function Animal(){ this.name = ""; this.say = function(){ console.log("hello"); } } function dog(){ this.name = "xiao"; //把Animal的方法應用到dog這個對象身上 Animal.apply(this,arguments); } console.log(new dog()); // dog { name: '', say: [Function] }
若是構造函數this綁定太多屬性,在實例化後會形成浪費,爲此咱們通常會使用原型鏈來優化,可是使用原型鏈以後咱們的apply和call的繼承方法就會失效,所以咱們通常使用混合的寫法。app
讓子的原型鏈指向父的實例(父實例化的對象)
dog.prototype = new Animal();函數
讓父的屬性建立在子的this上
Animal.call(this)優化
function Animal(name){ this.name = name; this.say = function(){ console.log("hello"); } } Animal.prototype.action = function() { console.log("running"); } function dog(name,type){ this.name = name; //把Animal的方法應用到dog這個對象身上 Animal.call(this,type); } dog.prototype = new Animal(); console.log(new dog('xiao', 'gold')); // Animal { name: 'gold', say: [Function] } (new dog('xiao')).action() //running
apply 傳遞一個數組或arguments,而call就要一個個地傳過this
es5中的繼承es5
function Reactangle(length,width) { this.length = length; this.width = width; } Reactangle.prototype.getArea = function(){ return this.length * this.width; } function Square(length) { Reactangle.call(this.length,length); } Square.prototype = Object.create(Reactangle.prototype,{ constructor: { value:Square, enumerable:true, writeable:true, configurable:true } }); var square = new Square(3); console.log(square.getArea()); console.log(square instanceof Square); console.log(square instanceof Reactangle);
在es6中實現繼承prototype
class Reactangle { constructor(length,width) { this.length = length; this.width = width; } getArea() { return this.length * this.width; } } class Square extends Reactangle { constructor(length) { // 等價於 Reactangle.call(this.length,length) super(length,length); } } var square = new Square(3); console.log(square.getArea()); // 9 console.log(square instanceof Square); // true