jquery 函数和常规 javascript 函数之间的区别?
像这样编写jquery函数有什么意义:
(function( $ ) {
$.fn.simple_hide_function = function() {
var $t = this;
$t.hide();
};
})( jQuery );
$(window).load(function () {
$('#myId').simple_hide_function();
});
为什么不这样做:
function simple_hide_function(id){
id.hide();
};
$(window).load(function () {
var my_id = $('#my_id');
simple_hide_function(my_id);
});
添加问题
这样做会有什么问题吗?
function simple_hide_function(id){
id.hide();
};
$(window).load(function () {
var my_id1 = $('#my_id1'),
my_id2 = $('#my_id2'),
my_id3 = $('#my_id3');
simple_hide_function(my_id1);
simple_hide_function(my_id2);
simple_hide_function(my_id3);
});
What't the point of writing jquery functions like this:
(function( $ ) {
$.fn.simple_hide_function = function() {
var $t = this;
$t.hide();
};
})( jQuery );
$(window).load(function () {
$('#myId').simple_hide_function();
});
Why not do it like this:
function simple_hide_function(id){
id.hide();
};
$(window).load(function () {
var my_id = $('#my_id');
simple_hide_function(my_id);
});
Added question:
Would it be any problem doing this?
function simple_hide_function(id){
id.hide();
};
$(window).load(function () {
var my_id1 = $('#my_id1'),
my_id2 = $('#my_id2'),
my_id3 = $('#my_id3');
simple_hide_function(my_id1);
simple_hide_function(my_id2);
simple_hide_function(my_id3);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在插件版本中,您将创建一个新函数并将其附加到 jQuery 对象。通过使函数成为对象的成员,您可以利用 jQuery 链接之类的功能,即在同一对象上连续调用多个函数。
在第二个版本中,您在全局范围内创建一个函数并向其传递一个 jQuery 对象。这会污染全局命名空间(现在你的函数在任何地方都可见),而且它并不真正符合 jQuery 哲学。
但是,正如您所发现的,功能上没有差异。两者都会执行得很好。
In the plugin version, you are creating a new function and attaching it to the jQuery object. By making your function a member of the object, you can take advantage of things like jQuery's chaining, where multiple functions are invoked on the same object in a row.
In the second version, you are creating a function in the global scope and passing it a jQuery object. This pollutes the global namespace (now your function is visible everywhere) and it just doesn't really fall in line with the jQuery philosophy.
However, as you've found, there are no functional differences. Both will execute fine.
我认为主要的想法是你没有弄乱全局命名空间。在第二个示例中,
simple_hide_function
属于窗口,可能会导致名称冲突,但在第一个示例中,它是一个局部变量。I think the main idea is that you are not cluttering up the global namespace. In your second example
simple_hide_function
belongs to the window, and could possibly cause a name conflict, but in the first example it is a local variable.