Mayur Arora
Mayur Arora

Reputation: 447

Calling a method of a function constructor from another function in the global scope - Javascript

I have the following function constructor

function myClass(funcList) {
this.markDone = function() {
console.log("Done");
}
this.execute = function() {
funcList.forEach(function(func){
func.apply(this);
}); 
}
}

and I have a couple of functions in the global-scope

function func1() {
console.log("func 1");
}

function func2() {
console.log("func 2");
}

var arr = [func1,func2];

I can call these functions from the class's context this way

var ob = new myClass(arr);
ob.execute(); //this does work

How do I invoke markDone from these functions func1 and func2.
If my func1 is

function func1() {
console.log("func 1");
markDone();
} 

and similarly for func 2

This does not work. Shouldn't apply with this take care of the context ?

Upvotes: 0

Views: 33

Answers (2)

Erik
Erik

Reputation: 327

You could do it this way

function myClass(funcList) {
    var myClass = this;
    this.markDone = function() {
        console.log("Done");
    }
    this.execute = function() {
        funcList.forEach(function(func){
            func.apply(myClass);
        });
    }
}

function func1() {
    console.log("func 1");
    this.markDone();
}

function func2() {
    console.log("func 2");
}

var arr = [func1,func2];

var ob = new myClass(arr);
ob.execute();

Upvotes: 0

deitch
deitch

Reputation: 14581

Close.

  1. You need to call this.markDone();
  2. this is set differently inside the forEach loop, so you need to set it explicitly or catch it earlier and set it to something else, like that

Try this:

function func1() {
    console.log("func 1");
    this.markDone();
} 

And:

this.execute = function() {
    var that = this;
    funcList.forEach(function(func){
        func.apply(that);
    }); 
}

Here is a fiddle http://jsfiddle.net/8649hu9s/1/

Upvotes: 2

Related Questions