2011-11-05 107 views
1

在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
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 
0

你会不得不暴露在privateMapBaseClass

BaseClass.prototype.privateMap = {"type": "BaseClass"}; 

然后你在ChildClass访问:

BaseClass.prototype.privateMap["type"] = "ChildClass";