This jQuery course建议定义您自己的 jQuery 实用程序函数作为组织代码的好方法。
但这并没有真正解释为什么。那么,为什么要编写这样的代码:
$.highlightResults = function(seats) {
//
}
$.highlightResults('/.seating-chart a');
优于简单:
function highlightResults(seats) {
//
}
highlightResults('/.seating-chart a');
类(class)是错误的,还是有充分的理由这样写?
最佳答案
$ 是一个 jQuery 函数对象或 jQuery 的别名。(更准确地说是 jQuery 函数,javascript 中的每个函数都是一个对象)。见What is the meaning of symbol $ in jQuery?
$.highlightResults => highlightResults is a property of jQuery object.
将任何函数定义为 jQuery 函数对象的属性时,您可以访问 jQuery 函数对象和 jQuery 的所有相关属性/函数通过函数内部的“this”。
举个简单的例子。
$.property1 ='a';
$.property2 ='b';
$.highlightResults = function(){
var concat = this.property1 + this.property2;
};
一切都与代码组织和行为有关。
如果你定义
function highlightResults(){xyxyxy;}
它不是 jQuery 函数对象的属性,位于 GLOBAL 空间
关于javascript - jQuery 实用函数是否优于普通函数定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8638233/