如何在JavaScript中访问继承方法内的私有属性
我试图调用一个继承的方法,该方法必须从当前对象访问私有属性。但它只接触公众,有什么不对 我的测试代码应该提醒两个变量:如何在JavaScript中访问继承方法内的私有属性,javascript,oop,inheritance,private,private-members,Javascript,Oop,Inheritance,Private,Private Members,我试图调用一个继承的方法,该方法必须从当前对象访问私有属性。但它只接触公众,有什么不对 我的测试代码应该提醒两个变量: function ParentClass(){ //Priviliged method to show just attributes this.priviligedMethod = function(){ for( var attr in this
function ParentClass(){
//Priviliged method to show just attributes
this.priviligedMethod = function(){
for( var attr in this ){
if( typeof(this[ attr ]) !== 'function' ){
alert("Attribute: " + this[ attr ]);
}
}
};
}
function ChildClass(){
// Call the parent constructor
ParentClass.call(this);
var privateVar = "PRIVATE VAR";
this.publicVAR = "PUBLIC VAR";
}
// inherit from parent class
ChildClass.prototype = new ParentClass();
// correct the constructor pointer because it points to parent class
ChildClass.prototype.constructor = ChildClass;
var objChild = new ChildClass();
objChild.priviligedMethod();
JSFIDLE版本:
提前感谢,,
亚瑟没有什么不对的。当您使用
var
关键字时,javascript会将该变量限制在当前定义的范围内
因此:
将仅从定义的块内部可见,即ChildClass()
查看这篇文章以获得更深入的解释。好的,但是当继承父类时,priviligedMethod也会被继承,因此从ChildClass调用它时,作用域应该与我声明的privateVar相同。在同一范围内,它必须是可访问的,或者不可访问?否,函数
priviliegedMethod
无法访问privateVar
。正如我所说,该变量被约束为ChildClass()
函数
var privateVar = "PRIVATE VAR";