Joey Ciechanowicz
Joey Ciechanowicz

Reputation: 3663

Call function so this not needed

I have an application that uses the v8 javascript engine, and within that I add functions to namespace objects that execute lines of code from the database. The contents of these functions need to not have this added before every function call. Following is some example code of my problem

var obj = {};
obj.method = function(a) { return a; }
obj.executor = function() { return method(5); }
obj.executor()
ReferenceError: method is not defined

var caller = function() { return method(5); }
caller.call(obj)
ReferenceError: method is not defined

As you can see, neither way allows me to call method without first adding this. Is there some way of executing a function so that it's context is set in such a way that this does not need to be added?

EDIT

This did work in a previous version of the v8 engine, but it seems the most recent one is not allowing it now.

Upvotes: 1

Views: 41

Answers (1)

cookie monster
cookie monster

Reputation: 10972

"The client's write rules which are the strings loaded from the database, and it was a requirement (who knows why) that they only need to write the function names and the application sorts out the scoping."

If you're not running in strict mode, you can use a with statement.

var obj = {};
obj.method = function(a) { return a; };
obj.executor = function() { 
    with (this) {
        return method(5);
    }
};
obj.executor();

var caller = function() { 
    with (this) {
        return method(5); 
    }
};

caller.call(obj);

Not saying this is a great solution, but it'll work if those are the requirements given.


I don't know your other requirements, but you can achieve this via a closure as well.

var obj = {};

(function() {
    var method = obj.method = function(a) { return a; };
    obj.executor = function() { 
        return method(5);
    };
}();

obj.executor();

Upvotes: 2

Related Questions