Skip to content Skip to sidebar Skip to footer

Pass Code As Function Argument In Javascript?

I'm trying to create a javascript framework by myself(so no jquery,mootools... code please) and I want to make the code for my framework only accessible in a framework function so

Solution 1:

Functions are first class objects in JavaScript. You can pass them around in the same way as Strings, Numbers, Arrays or any other data type.

var foo = function () { alert(1); };
var bar = function (arg) { arg(); }
bar(foo);

Solution 2:

in javascript, a function is exactly a variable, the code you mentioned:

$(document).ready( function () {//code});

is in fact declared a function without a name, and then passed it as an argument to "ready()". Thus, your mind of pass code to function in the way

frameworkname( {} );

is illegal because "{}" is a code block but not any kind of "variable"

Solution 3:

In JavaScript, variables can represent any data type. Therefore, in function frameworkname( x ) { } can take an argument of any type (function, object, primitive, etc).

function frameworkname( x ) {
    if ( typeof x === "function" ) {
        x(); // function passed
    } else if ( typeof x === "object" ) {
        for ( var i in x ) {
           // Object passed
           x[i]();
        }
    }
}
frameworkname(function() {
    alert("function passed as argument");
});
frameworkname({
    hello: function() {
         alert("hello");
    }
});

Solution 4:

I think something like this:

functionframeworkname(){

  this.ready = function(code){
      code();
  };
  returnthis;
}

frameworkname().ready(function(){
  console.log('Function executed'); 
});

Post a Comment for "Pass Code As Function Argument In Javascript?"