ajs*_*sie 559 javascript jquery
这fn意味着什么?
jQuery.fn.jquery
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 843
在jQuery中,fn属性只是属性的别名prototype.
该jQuery标识符(或$)仅仅是一个构造函数,并用它创建的所有实例,从构造函数的原型继承.
一个简单的构造函数:
function Test() {
this.a = 'a';
}
Test.prototype.b = 'b';
var test = new Test();
test.a; // "a", own property
test.b; // "b", inherited property
Run Code Online (Sandbox Code Playgroud)
一个类似于jQuery体系结构的简单结构:
(function() {
var foo = function(arg) { // core constructor
// ensure to use the `new` operator
if (!(this instanceof foo))
return new foo(arg);
// store an argument for this example
this.myArg = arg;
//..
};
// create `fn` alias to `prototype` property
foo.fn = foo.prototype = {
init: function () {/*...*/}
//...
};
// expose the library
window.foo = foo;
})();
// Extension:
foo.fn.myPlugin = function () {
alert(this.myArg);
return this; // return `this` for chainability
};
foo("bar").myPlugin(); // alerts "bar"
Run Code Online (Sandbox Code Playgroud)
And*_*y E 144
jQuery.fn是为了简化而定义的jQuery.prototype.从源代码:
jQuery.fn = jQuery.prototype = {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这意味着jQuery.fn.jquery是一个别名jQuery.prototype.jquery,它返回当前的jQuery版本.再次从源代码:
// The current version of jQuery being used
jquery: "@VERSION",
Run Code Online (Sandbox Code Playgroud)
Tra*_*s J 143
fn字面意思是指jquery prototype.
这行代码在源代码中:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
Run Code Online (Sandbox Code Playgroud)
但真正的工具背后fn是它可以将你自己的功能挂钩到jQuery中.请记住,jquery将是函数的父作用域,因此this将引用jquery对象.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
Run Code Online (Sandbox Code Playgroud)
所以这是一个简单的例子.让我们说我想做两个扩展,一个放蓝色边框,然后将文本颜色为蓝色,我希望它们被链接.
jsFiddle Demo$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Run Code Online (Sandbox Code Playgroud)
现在你可以对这样的类使用它们:
$('.blue').blueBorder().blueText();
Run Code Online (Sandbox Code Playgroud)
(我知道这最好用css完成,例如应用不同的类名,但请记住这只是一个展示概念的演示)
这个答案有一个完整的扩展的好例子.
小智 19
$ .fn是jQuery.prototype的别名,它允许您使用自己的函数扩展 jQuery。
例如:
$.fn.something = function{}
Run Code Online (Sandbox Code Playgroud)
将允许你使用
$("#element").something()
Run Code Online (Sandbox Code Playgroud)
$ .fn也是jQuery.fn 的同义词。
| 归档时间: |
|
| 查看次数: |
259940 次 |
| 最近记录: |