简体   繁体   English

在javascript中将代码作为函数参数传递?

[英]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 for example, something like this: 我正在尝试自己创建一个javascript框架(所以没有jquery,mootools ...代码请),我想让我的框架的代码只能在框架函数中访问,例如,像这样:

frameworkname({
//framework code here
});

so my framework code doesn't conflict with other frameworks. 所以我的框架代码不会与其他框架冲突。 I know that frameworkname({}); 我知道frameworkname({}); is a function, but I don't know how you pass code as a function argument. 是一个函数,但我不知道如何将代码作为函数参数传递。 I know this is possible as I'm quite experienced in jquery and jquery has that stuff everywhere (example: $(document).ready(function(){//codehere}); ), but how did the jquery developers do this? 我知道这是可能的,因为我在jquery中很有经验,jquery到处都有这些东西(例如: $(document).ready(function(){//codehere}); ),但jquery开发人员是如何做到这一点的呢? I want to be able to do this for my framework. 我希望能够为我的框架做到这一点。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

Functions are first class objects in JavaScript. 函数是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);

in javascript, a function is exactly a variable, the code you mentioned: 在javascript中,函数只是一个变量,你提到的代码:

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

is in fact declared a function without a name, and then passed it as an argument to "ready()". 事实上,它被声明为没有名称的函数,然后将其作为参数传递给“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" 是非法的,因为“{}”是一个代码块,但不是任何一种“变量”

In JavaScript, variables can represent any data type. 在JavaScript中,变量可以表示任何数据类型。 Therefore, in function frameworkname( x ) { } can take an argument of any type (function, object, primitive, etc). 因此,在function frameworkname( x ) { }可以采用任何类型的参数(函数,对象,原语等)。

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");
    }
});

I think something like this: 我认为这样的事情:

function frameworkname(){

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM