如何在 JavaScript 中访问继承方法内的私有属性
我正在尝试调用必须访问当前对象的私有属性的继承方法。但它只能访问公共的,有什么问题吗?
我的测试代码应该提醒两个变量:
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();
jsfiddle 版本: http://jsfiddle.net/gws5s/6/
提前致谢, 亚瑟
I am trying to call a inherited method that must access private attributes from current object. But it only access the public ones, what is wrong?
My test code should alert both vars:
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();
The jsfiddle version: http://jsfiddle.net/gws5s/6/
Thanks in advance,
Arthur
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没什么问题。当您使用
var
关键字时,javascript 将使该变量仅限于当前定义的当前范围。so:
仅在其定义的块内部可见,即
ChildClass( )
看看这个文章 的更深入的解释。
Nothing is wrong. When you use the
var
keyword, javascript will make that variable limited to the current scope it is currently defined in.so:
will only be visible from inside the block it is defined, namely
ChildClass()
Check out this article for a more in-depth explanation.