1

In my example below based on some conditions I should either call foo method from my class or foo method from alternative.js; I'm assigning method in myFunc variable and call that variable however if I want to call foo method of myClass, it breaks because name gets undefined in MyClass.prototype.myclass. Is there any workaround here? Please let me know if you need more clarification:

    MyClass.prototype.test = function(name) {
        var myClass;
        var myFunc;
        shouldWork = true;
        if(shouldWork){
            p = require('alternative.js')
            myFunc = p['foo'];
        }else{
            myClass= this.myclass(name);
            myFunc = myClass['foo'];

        }

        myFunc('bar');// if "shouldWork" is true it works, but if it is false, it fails
        //In other words, myClass.foo('bar') works but calling
       //the variable which is set to myClass['foo']


    }
    MyClass.prototype.myclass = function(name) {
        // Here I do some operations on name and if it is undefined it breaks!
        // name gets undefined if you foo method of myClass if you have it in
        //a variable, becuse it is not assiging name which is from prototype
    }
  • 1
    Your question has three different capitalizations of `myclass` which is really confusing. Please do not intentionally write code that way. If this is a mistake, then please correct your question. Also, you have a local variable called `myclass` and an instance property called `myclass`. That is again a really confusing scenario. Please give variables very descriptive names and do not make multiple variables highly similar. – jfriend00 Sep 14 '15 at 23:33
  • jfriend00 Sorry for that! Thanks so much anyway :-) –  Sep 14 '15 at 23:42
  • I'll keep your advise in mind... It was hard to replicate a simple example of my problem.... –  Sep 14 '15 at 23:43

1 Answers1

0

You can use .bind() to bind the object to the method call. For example, if you're trying to save a method of a specific object into myFunc, then you can do this:

myFunc = myClass.foo.bind(myClass);

Then, when you later do:

myFunc(...);

it will actually use the object reference myClass to call it properly as a method.

See the MDN reference on .bind() for more details.

jfriend00
  • 683,504
  • 96
  • 985
  • 979