开发者

Define a function that will be implemented by the user

I have the following example code

var object = {
    userDefinedFunction : function(){
        //no implementation, this will be defined by the user
    }
}

What i want to achieve is the user giving his own implementation of it:

object.userDefinedFunction = function(){
    alert("just testing");
}

I tested this and works as i expected, what i want to know is:

  • is this the javascript way of solving this kind of problem?
  • let's say that it's mandatory that userDefinedFunction is implemented, how do i make sure of this? I could rely on something like the following, checking for implemented, but i'm learning javascript so i want to know how to leverage the language:

    userDefinedFunction : function(){
        implemented =开发者_如何学JAVA false;
    }
    

Thank you.


I don't know if this is the way to go, but if your object has to be initialized somehow by the user, you can test in this function, whether userDefinedFunction is defined and throw an exception if not.

One idea that feels to be a cleaner implementation, is to let the user provide some kind of configuration object that defines the functions, something like:

yourObject.initialize({
    userDefinedFunction: function() {}
});


You could throw an error in the default implementation:

var object = {
    userDefinedFunction : function(){
        throw "userDefinedFunction must be implemented";
    }
}

or show an alert box, depending on your application.


var object = {
    userDefinedFunction : undefined,
    anotoherDefinedFunc : undefined,

    /* ... */

    hasUserImplementedInterfaces : function() {
        if (typeof object.userDefinedFunction !== 'function') return false;
        if (typeof object.anotoherDefinedFunc !== 'function') return false;
        /*  ... */
        return true;
    }

};

console.log(object.hasUserImplementedInterfaces());

hasUserImplementedInterfaces() function checks for user function implementations so you can execute as first check using that object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜