Matan L
Matan L

Reputation: 1027

Javascript methods use

I am trying to create a class in JavaScript that would be inherited and than some of its methods would be overridden.

I am using the following structure :

function MyClass()
{
    this.myvar = null;
    this.someotherVar = { someFunction: function(a,b){ function1(a,b); })

}

// some functions 
MyClass.prototype.functionA =  function() {..}
MyClass.prototype.functionB =  function() {functionC();}

//some functions that would be overrided
MyClass.prototype.function1=  function() {...}
MyClass.prototype.functionC=  function() {...}

Now I have 2 problems:

  1. Might functionC be a problem to use in functionB because it is defined afterwards?

  2. How can I relate to function1 inside someFunction in the right way?

Upvotes: 0

Views: 30

Answers (1)

Felix Kling
Felix Kling

Reputation: 816414

1. Might functionC be a problem to use in functionB because it is defined afterwards?

No. You just have to call it properly:

 function() { this.functionC(); }
 //           ^^^^^

otherwise the function won't be found.

Of course you also have to make sure that functionB is only called once functionC is defined.

2. How can I relate to function1 inside someFunction in the right way?

A tiny problem is that someFunction is not a method of the instance but of another object. To still call the correct function1, you can store a reference to the instance in a variable:

function MyClass() {
    var self = this;
    this.myvar = null;
    this.someotherVar = { 
        someFunction: function(a,b){ 
            self.function1(a,b);
        }
    };
}

Upvotes: 1

Related Questions