在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;
最佳答案
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
关于javascript - 从子类中访问基类变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8017677/