2011-09-29 69 views
3

我想學習如何在JavaScript中使用'類'。JavaScript類繼承

這裏是我的代碼:

function Shape(x, y) { 
    this.x= x; 
    this.y= y;  
} 

Shape.prototype.toString= function() { 
     return 'Shape at '+this.x+', '+this.y; 
    }; 

function Circle(x, y, r) { 
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords 
    this.r= r; 
} 
Circle.prototype= $.extend(true, {}, Shape.prototype); 

Circle.prototype.toString= function() { 
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r; 
} 

var c = new Circle(1,2,3); 
alert(c); 

有沒有一種方法來定義它的構造函數中的該形狀的toString功能,或者它不會在這種情況下,有意義嗎?

+0

在這種情況下'this.toString = function(){...}'不起作用嗎? – Connell

+0

不,它不是。看到區別: http://jsfiddle.net/paptamas/qDSkj/ 和 http://jsfiddle.net/paptamas/cbnLB/ –

+1

原型是正確的方法。它會創建一次toString函數。在構造函數中,每個新建都會創建它。 – Joe

回答

0

此基礎上我的理解:

  1. 當你移動的ToString()到構造那麼的ToString()成爲您的實例的明確成員。因此任何對.toString()的調用都會觸發該顯式成員。

實施例:http://jsfiddle.net/paptamas/qDSkj/

  1. 但是當你定義爲原型,(在不存在所謂的ToString顯式構件的()),以任何的ToString()方法調用將閃光。 toString()函數是爲調用對象的類型定義的(Circle是你的情況)。

例子:http://jsfiddle.net/paptamas/cbnLB/

換句話說,明確成員對原型定義的優先級,當你說

this.toString = function() ... 

你是定義該功能爲您的實例的成員(如反對你的類型的成員 - 這是在一種沒有優化的方式)。

問候。