Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中访问继承方法内的私有属性_Javascript_Oop_Inheritance_Private_Private Members - Fatal编程技术网

如何在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";