【问题标题】:How to access private attributes inside an inherited method in JavaScript如何在 JavaScript 中访问继承方法中的私有属性
【发布时间】:2012-02-28 04:57:36
【问题描述】:

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

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

            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/

提前致谢, 亚瑟

【问题讨论】:

    标签: javascript oop inheritance private private-members


    【解决方案1】:

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

    所以:

    var privateVar = "PRIVATE VAR";
    

    只会在它定义的块内部可见,即ChildClass()

    查看此article 以获得更深入的解释。

    【讨论】:

    • 好的,但是当继承 ParentClass 时,它也被继承了 priviligedMethod,因此从 ChildClass 调用它的范围应该与我声明的 privateVar 相同。在同一范围内,它必须是可访问的,还是不可访问的?
    • 不,函数priviliegedMethod 无法访问privateVar。就像我说的,该变量被限制在 ChildClass() 函数中
    猜你喜欢
    • 2013-09-04
    • 2012-01-05
    • 2011-04-30
    • 2018-04-21
    • 1970-01-01
    • 2020-02-11
    • 2021-05-07
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多