2011-11-05 464 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";