0

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

1 Answer 1

1

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:

var privateVar = "PRIVATE VAR";

will only be visible from inside the block it is defined, namely ChildClass()

Check out this article for a more in-depth explanation.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, but when a inherit the ParentClass the priviligedMethod it is inherited too, so calling it from the ChildClass the scope should be the same that i declared the privateVar. In the same scope it must be accessable, or not?
no, the function priviliegedMethod has no way of accessing the privateVar. Like I said, that variable is constrained to the ChildClass() function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.