jQuery实用函数是否比普通函数定义更好?

4

这个jQuery课程推荐定义自己的jQuery实用函数作为组织代码的好方法。

但它并没有真正解释为什么。那么,为什么编写以下代码:

$.highlightResults = function(seats) {
  // 
}
$.highlightResults('/.seating-chart a');

更好的选择是简单地:

function highlightResults(seats) { 
 //
}
highlightResults('/.seating-chart a');

这门课程是错误的,还是有写成这样的好理由?

1
不要混淆全局“命名空间”。 - Rob W
1个回答

2

$ 是 jQuery 函数对象或 jQuery 的别名。(更准确地说,jQuery 函数及 JavaScript 中的每个函数都是一个对象)。详见What is the meaning of symbol $ in jQuery?

 $.highlightResults => highlightResults is a property of jQuery object.

当您将任何函数定义为jQuery函数对象的属性时,您可以通过“this”在函数内部访问jQuery函数对象和所有关联的属性/函数。

以一个简单的例子为例。

$.property1 ='a';
$.property2 ='b';
$.highlightResults = function(){
                                 var concat = this.property1 + this.property2;
                               };

这都与代码组织和行为有关。

如果你定义了

function highlightResults(){xyxyxy;} 

它不是jQuery函数对象的属性,而是位于全局空间


$不就是jQuery函数吗?当然它是一个函数对象,但"jQuery对象"听起来像是"jQuery封装实例"。 - Bergi
谢谢,现在更有意义了。 - Richard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接