js-*_*der 29 javascript jquery
jQuery或$似乎是一个功能:
typeof $; // "function"
Run Code Online (Sandbox Code Playgroud)
它就像一个:
$('div').removeClass(); // $ constructs a new object with some methods like removeClass
Run Code Online (Sandbox Code Playgroud)
但是当我删除函数括号时,它的行为就像一个对象:
$.each(/* parameters */); // $ is an object with some methods like each
Run Code Online (Sandbox Code Playgroud)
我想知道这是如何可行的,以及如何将这种行为实现到我自己的函数中.
Rob*_*b W 33
函数也是对象,因此$.each可以以与Object类似的方式定义.
JavaScript是一种原型语言.对于jQuery,这意味着每个实例都$从中继承方法jQuery.prototype.见注释
一个非常粗略的演示,实现类似的行为:
(function() { // Closure to not leak local variables to the global scope
function f(a, b) {
//Do something
}
// Prototype. All properties of f.prototype are inherited by instances of f.
// An instance of f can be obtained by: new f, new f(), Object.create(f)
f.prototype.removeClass = function(a) {
return a;
};
function $(a, b) {
return new f(a, b); // <--- "new f" !
}
$.each = function(a) {
alert(a);
};
window.$ = $; // Publish public methods
})();
//Tests (these do not represent jQuery methods):
$.each("Foo"); // Alerts "Foo" (alert defined at $.each)
alert($().removeClass('Blabla'));// Alerts "Blabla"
Run Code Online (Sandbox Code Playgroud)
jQuery的root方法定义如下(仅显示相关部分):
(function(win) {
var jQuery = function (selector, context) {
return new jQuery.fn.init(selector, context, rootjQuery);
};
//$.fn = jQuery.fn is a shorthand for defining "jQuery plugins".
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( /* ..parameters.. */ ) {
//.... sets default properties...
}
//....other methods, such as size, get, etc...
//.... other properties, such as selector, length, etc...
};
jQuery.fn.removeClass = function() { // (Actually via jQuery.fn.extend)
// ... method logic...
}; //...lots of other stuff...
win.$ = win.jQuery = jQuery; //Publish method
})(window);
Run Code Online (Sandbox Code Playgroud)
该prototype方法的优点是链接方法和属性非常容易.例如:
$("body").find("div:first").addClass("foo");
Run Code Online (Sandbox Code Playgroud)
实现此功能的方法可以是:
$.fn.find = function(selector) {
...
return $(...);
};
Run Code Online (Sandbox Code Playgroud)
如果您对jQuery的实际实现感兴趣,请查看带注释的源代码:
jQuery.fn.extend用于向jQuery 添加removeClass等.rec*_*ive 10
所有功能都以这种方式工作
function fn() {
alert("hi mom");
}
fn.foo = "bar";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3428 次 |
| 最近记录: |