0

Im trying to call a function/Method in javscript using OOP style but from a different context.

for example:

var SomeClass = function(){
    this.init = function(){
        var something = "An Interesting Variable";
        this.foo(something); //this works fine
    },
    this.foo = function(bar){
        alert(bar);
    }
    this.foo2 = function(){
        this.foo(something); // this deos not work/ something is not defined
    }

};

var newClass = new SomeClass();
newClass.init();
newClass.foo2();

so basically i want to call this.foo() function within the this.foo2() context, but acting as the this.init(), im not sure this makes sense, but im new to OOP in javascript.

1 Answer 1

2

Your context is right, but you're trying to access a variable that isn't defined in that scope. The variable something, declared with var within init will only live inside that function.

You need to make it a member of SomeClass:

this.init = function() {
   this.something = 'An interesting variable';
   this.foo(this.something);
},

this.foo2 = function() {
   this.foo(this.something);
}
Sign up to request clarification or add additional context in comments.

Comments

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.