从子类中访问基类变量

时间:2011-11-05 02:10:17

标签: javascript inheritance

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

2 个答案:

答案 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