在些JavaScript類定義的時(shí)候,大家很可能都寫過下面的代碼:
function A() {}
function B() {}
B.prototype = new A()
上面這樣寫是為了讓instanceof語句能起作用。舉個(gè)例子:
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的作用是可以用來模擬繼承,使我們?cè)诟割惱锾砑拥膶傩苑椒ㄔ谧宇惱锬茉L問。
但是我們可以使用一種其他的方法來變通。
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)
這時(shí)b中絕對(duì)有x,并且x 等于1,但是我們?yōu)槭裁催€要使用prototype呢?
主要是為了向父類原型動(dòng)態(tài)添加的屬性和方法可以出現(xiàn)在子類的實(shí)例對(duì)象中。
接著上面的例子
A.prototype.z = function () {}
如果我們沒有設(shè)置B.prototype = new A(),則b不會(huì)動(dòng)態(tài)添加方法z 。