Hasan
Hasan

Reputation: 65

JavaScript function after object is created

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?

Upvotes: 1

Views: 963

Answers (4)

ken_o
ken_o

Reputation: 384

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");
};

Upvotes: 0

laser
laser

Reputation: 570

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();

Upvotes: 0

Matthew Herbst
Matthew Herbst

Reputation: 31993

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

function method2() {
  alert(2);
}

var c = new Context();
c.run();

Upvotes: 2

Stephan Bijzitter
Stephan Bijzitter

Reputation: 4595

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.

Upvotes: 1

Related Questions