Rasmus Brandberg
Rasmus Brandberg

Reputation: 3

Pass javascript function as parameter and evaluate its content as class content

Is it possible to pass a function as parameter to a method and evaluate it's content as if it was part of the class?

function Class()
{
    this.Method = function( param )
    {
        // Call "CallThis"
    };

    this.CallThis = function()
    {

    };
}

var c = new Class();
c.Method(
    {
        evalThisContent: function()
        {
            this.CallThis();
        }
    }
);

Upvotes: 0

Views: 3041

Answers (3)

Brett Zamir
Brett Zamir

Reputation: 14345

I've modified the class in the way I think you may have intended, though Zirak seems to have already demonstrated the main idea.

function Class() {
}
Class.prototype.method = function(param) {
    if (typeof param === 'object' && param.evalThisContent) {
        param.evalThisContent.call(this);
    }
};
Class.prototype.callThis = function() {
    alert("I'm getting called indirectly!");
};

var c = new Class();
c.method(
    {
        evalThisContent: function()
        {
            this.callThis();
        }
    }
);

If you wish, you could instead add or alter "evalThisContent" dynamically on the prototype, making it available to all objects which may henceforth wish to call it:

Class.prototype.method = function(param) {
    if (typeof param === 'object' && param.evalThisContent && !Class.prototype.evalThisContent) {
        Class.prototype.evalContent = param.evalThisContent;
    }
    this.evalContent();
};

This has the advantage of not creating a function into memory each time, nor invoking it in a less than optimal way with call, while call (or apply), as in the first example, has the more commonly useful advantage of allowing each instance of the Class to use its own functions or implementations (or you could use inheritance).

Upvotes: 0

Zirak
Zirak

Reputation: 39808

If I follow your intention:

function Class()
{
    this.Method = function( param, name )
    {
        this[name] = param;
        param.call(this);
    };

    this.CallThis = function()
    {

    };
}

var c = new Class();

c.Method(function() {
    this.CallThis();
}, 'evalThisContent');

Upvotes: 1

Jim Blackler
Jim Blackler

Reputation: 23169

It's certainly possible to invoke the function, in this case with

param()

as for "as if it was part of the class", if you mean would it have access to its members through this, no it wouldn't. But you could pass in a reference to this (object of type Class) to the function and it could access its members through this reference.

Upvotes: 1

Related Questions