在些JavaScript類定義的時候,大家很可能都寫過下面的代碼:
function A() {}
function B() {}
B.prototype = new A()
上面這樣寫是為了讓instanceof語句能起作用。舉個例子:
1.不重寫子類的prototype屬性
b = new B();
b instanceof B //return true
b instanceof A //
return false
b instanceof Object //return true
2.寫子類的prototype屬性
b = new B();
b instanceof B //return true
b instanceof A //
return true
b instanceof Object //return true
另外,prototype的作用是可以用來模擬繼承,使我們在父類里添加的屬性方法在子類里能訪問。
但是我們可以使用一種其他的方法來變通。
function A(x) {
this.x = x;
this.method1 = functioni () {};
}
function B(x,y) {
A.call(this,x);
this.y = y;
}
b = new B(1, 2)
這時b中絕對有x,并且x 等于1,但是我們為什么還要使用prototype呢?
主要是為了向父類原型動態添加的屬性和方法可以出現在子類的實例對象中。
接著上面的例子
A.prototype.z = function () {}
如果我們沒有設置B.prototype = new A(),則b不會動態添加方法z 。