JavaScript原型扩展

Dov*_*ius 3 javascript variables prototype global extending

我正在尝试扩展一个Abstract对象.

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());
Run Code Online (Sandbox Code Playgroud)

结果:

ItemB
ItemA
a
Run Code Online (Sandbox Code Playgroud)

我在ItemB实例中获得ItemA的范围有什么特别的原因吗?我该如何解决?

Amb*_*mps 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;
Run Code Online (Sandbox Code Playgroud)

虽然在这种情况下ItemB.getC()将返回undefined.