如何在JavaScript中访问继承方法内部的私有属性

How to access private attributes inside an inherited method in JavaScript

本文关键字:内部 属性 方法 继承 JavaScript 访问      更新时间:2023-09-26

我正在尝试调用一个继承的方法,该方法必须访问当前对象的私有属性。但它只访问公共的,这有什么错?

我的测试代码应该提醒两个变量:

            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/

提前感谢,Arthur

没有任何问题。当您使用var关键字时,javascript会将该变量限制在当前定义的范围内。

所以:

var privateVar = "PRIVATE VAR";

将仅从定义的块内部可见,即ChildClass()

查看本文以获得更深入的解释。