Javascript構(gòu)造函數(shù)繼承

2018-01-06 19:14 更新

Javascript面向?qū)ο笤O(shè)計(jì) - Javascript構(gòu)造函數(shù)繼承


構(gòu)造函數(shù)繼承是通過從構(gòu)造函數(shù)重置原型來完成的。


function Rectangle(length, width) {  
    this.length = length; //from w ww  . j  av a  2  s  .co m
    this.width = width; 
} 

Rectangle.prototype.getArea = function() { 
    return this.length * this.width; 
}; 

Rectangle.prototype.toString = function() { 
    return "[Rectangle " + this.length + "x" + this.width + "]"; 
}; 

// Square inherits from Rectangle 
function Square(size) {  
    this.length = size; 
    this.width = size; 
} 

Square.prototype = new Rectangle(); 
Square.prototype.constructor = Square; 

Square.prototype.toString = function() { 
    return "[Square " + this.length + "x" + this.width + "]"; 
}; 

var rect = new Rectangle(5, 10); 
var square = new Square(6); 

console.log(rect.getArea());        // 50 
console.log(square.getArea());      // 36 

console.log(rect.toString());       // "[Rectangle 5x10]" 
console.log(square.toString());     // "[Square 6x6]" 

console.log(rect instanceof Rectangle);     // true 
console.log(rect instanceof Object);        // true 

console.log(square instanceof Square);      // true 
console.log(square instanceof Rectangle);   // true 
console.log(square instanceof Object);      // true 

上面的代碼生成以下結(jié)果。



構(gòu)造函數(shù)偷

您可以使用call()或apply()從子類型構(gòu)造函數(shù)調(diào)用超類型構(gòu)造函數(shù)傳入新創(chuàng)建的對(duì)象。 實(shí)際上,你“偷了超類構(gòu)造函數(shù)為您自己的對(duì)象,如在這個(gè)例子:


function Rectangle(length, width) { 
    this.length = length; /*w w  w  .  j  a va 2  s .com*/
    this.width = width; 
} 
Rectangle.prototype.getArea = function() { 
    return this.length * this.width; 
}; 

Rectangle.prototype.toString = function() { 
    return "[Rectangle " + this.length + "x" + this.width + "]"; 
}; 

// inherits from Rectangle 
function Square(size) {  
    Rectangle.call(this, size, size); 
    // optional: add new properties or override existing ones here 
} 

Square.prototype = Object.create(Rectangle.prototype, { 
                        constructor : { 
                            configurable : true, 
                            enumerable : true, 
                            value : Square, 
                            writable : true 
                        } 
                    }); 

Square.prototype.toString = function() { 
    return "[Square " + this.length + "x" + this.width + "]"; 
}; 

var square = new Square(6); 

console.log(square.length);         // 6 
console.log(square.width);          // 6 
console.log(square.getArea());      // 36 

上面的代碼生成以下結(jié)果。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)