在javascript中,子类可以访问&更改基类变量?如果没有,是否有办法创建特权变量?我知道你可以创建特权函数,但特权变量呢?
这是我的尝试:
function BaseClass()
{
var privateMap = {"type": "BaseClass"};
}
function ChildClass()
{
// How can I access BaseClass's private variable privateMap?
privateMap["type"] = "ChildClass";
}
ChildClass.prototype = new BaseClass();
ChildClass.prototype.constructor = ChildClass;
答案 0 :(得分:0)
您必须在privateMap
中公开BaseClass
:
BaseClass.prototype.privateMap = {"type": "BaseClass"};
然后您可以在ChildClass
中访问它:
BaseClass.prototype.privateMap["type"] = "ChildClass";
答案 1 :(得分:0)
var Base = function()
{
var privateMap = {"type":"Base"};
this.changeMap = function(arg) {
privateMap['type'] = arg;
console.log('Changed Map to ' + privateMap['type'])
}
}
var Child = new Base;
Child.changeMap('Child1')
console.log(Child.privateMap)//undefined