开发者

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();
        }
   开发者_运维问答 }
);


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


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜