简体   繁体   English

JavaScript原型扩展

[英]JavaScript prototype extending

I'm trying to extend an Abstract object. 我正在尝试扩展一个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());

The result: 结果:

ItemB
ItemA
a

Is there any particular reason why I'm getting ItemA's scope in ItemB instance? 我在ItemB实例中获得ItemA的范围有什么特别的原因吗? How can I fix it? 我该如何解决?

It is because you are using global variables. 这是因为你正在使用全局变量。 Fix it by using this keyword: 使用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;

Although in this case ItemB.getC() will return undefined. 虽然在这种情况下ItemB.getC()将返回undefined。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM