1

I have a context function type that is defined as below:

var Context = function () {

    this.run = function () {
        method1();
        method2();
    }

    var method1 = function () {
    }
}

As it is clear in the definition, method2 is not defined in the context. I need every instance of Context passes its implementation of this method.

var c = new Context();

// This does not work! because the call in run() function 
// is not this.method2();

c.method2 = function () {
    alert("injected method2");
};

c.run();

I need to keep method2() in run without use of this object i.e. this.method2();

Any solution?

Hasan
  • 65
  • 8

4 Answers4

2

If you can define method2 before creating Context it will work no problem:

function method2() {
  alert(2);
}

var c = new Context();
c.run();
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • Note that my answer is basically equivalent to @Stephan Bijzitter's, since in the global scope defining a function attaches (hoists) it to the `window` scope. His answer will not work however if you are say, inside a React module. – Matthew Herbst Feb 08 '17 at 18:47
  • Thanks that solves my problem. I can actually put it all in a self calling function to avoid any conflicts. – Hasan Feb 08 '17 at 19:01
  • Although there's no need to define it _before_, as hoisting will make it available anyway – Stephan Bijzitter Feb 08 '17 at 23:17
  • Very true, so long as it's defined as `function x()` instead of `const x = function()` – Matthew Herbst Feb 09 '17 at 00:08
1

You can add method2 to the window object instead of the c object, in which case it will work.

Note that this is a clear indicator of poor design. You should probably look into doing this differently.

Stephan Bijzitter
  • 4,425
  • 5
  • 24
  • 44
0

Callback approach:

var Context = function (callback) {

    this.run = function () {
        method1();
        if(callback) callback();
    }

    var method1 = function () {
    }
}

var c = new Context(function () {
    alert("injected method2");
});

c.run();
laser
  • 570
  • 4
  • 20
  • I cannot accept this, because you changed the definition of **Context**. – Hasan Feb 08 '17 at 18:56
  • @Hasan Do you mean that you want to add prototype? Context.prototype.method2 = function() {}? http://stackoverflow.com/questions/13521833/javascript-add-method-to-object – laser Feb 08 '17 at 18:58
0

If you change your run method to the following it should work as expected

this.run = function () {
    method1();
    this.method2();
}

UPDATE: I just realized it looks like you want to be able to do this on all instances of Context objects. In that case you would also need to define method2 on Context.prototype and not just on c

Context.prototype.method2 = function () {
    console.log("injected method2dfd");
};
ken_o
  • 374
  • 2
  • 8