2013-03-03 95 views
3

我想要擴展一個抽象對象。JavaScript原型擴展

var Abstract = function() { code = 'Abstract'; }; 
Abstract.prototype.getCode = function() { return code; }; 
Abstract.prototype.getC = function() { return c; }; 

var ItemA = function() { code = 'ItemA'; c = 'a'; }; 
ItemA.prototype = Object.create(Abstract.prototype); 
ItemA.prototype.constructor = ItemA; 

var ItemB = function() { code = 'ItemB'; }; 
ItemB.prototype = Object.create(Abstract.prototype); 
ItemB.prototype.constructor = ItemB; 

var b = new ItemB(); 
console.log(b.getCode()); 
var a = new ItemA(); 
console.log(b.getCode()); 
console.log(b.getC()); 

結果:

ItemB 
ItemA 
a 

有,爲什麼我得到意達的範圍,例如ItemB什麼特別的原因?我該如何解決它?

回答

7

這是因爲你正在使用全局變量。通過使用this關鍵字對其進行修復:

var Abstract = function() { this.code = 'Abstract'; }; 
Abstract.prototype.getCode = function() { return this.code; }; 
Abstract.prototype.getC = function() { return this.c; }; 

var ItemA = function() { this.code = 'ItemA'; this.c = 'a'; }; 
ItemA.prototype = Object.create(Abstract.prototype); 
ItemA.prototype.constructor = ItemA; 

var ItemB = function() { this.code = 'ItemB'; }; 
ItemB.prototype = Object.create(Abstract.prototype); 
ItemB.prototype.constructor = ItemB; 

雖然在這種情況下ItemB.getC()將返回undefined。