这是你如何在jQuery中定义一个函数? [英] Is this how you define a function in jQuery?

查看:90
本文介绍了这是你如何在jQuery中定义一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是你在jQuery中定义一个函数的方法吗?

Is this how you define a function in jQuery?

$(document).ready( function () {
    var MyBlah = function($blah) { alert($blah);  };
 });

现在调用我的函数:

MyBlah('hello');


推荐答案

首先,您的代码有效并且有效在JavaScript中创建函数的方法(jQuery除外),但是因为你在另一个函数中声明一个函数(在这种情况下是一个匿名函数),MyBlah将无法从全局范围访问。

First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.

以下是一个例子:

$(document).ready( function () {

    var MyBlah = function($blah) { alert($blah);  };

    MyBlah("Hello this works") // Inside the anonymous function we are cool.

 });

MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)

这是(有时)一个理想的行为,因为我们不会污染全局命名空间,所以如果你的函数不需要从代码的其他部分调用,那么这是要走的路。

This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.

在匿名函数之外声明它将它放在全局命名空间中,并且可以从任何地方访问它。

Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.

最后,不需要变量名开头的 $ ,有时当变量是jQuery对象本身的一个实例时用作jQuery约定(在这种情况下不一定) )。

Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).

也许你需要的是创建一个 jQuery插件,这非常简单有用,因为它可以让你做这样的事情:

Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:

$('div#message').myBlah("hello")

参见: http://www.re-cycledair.com/creating-jquery-plugins

这篇关于这是你如何在jQuery中定义一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆