我的理解是JavaScript中的函数可以具有状态.有些州只需要初始化一次.你是怎么做到这样调用函数不重新初始化它们?
例如,$()在jQuery中是一个函数,而不是一个对象,但它似乎有状态并且像一个对象.
我想为此创建一个对象,但我想要的实际上是一个外观函数,就像$()工作方式一样.
功能是对象.他们可以有属性:
function F() {}
F.key = "value";
alert(F.key) // "value"
Run Code Online (Sandbox Code Playgroud)
您还可以将函数用作调用的构造函数new:
function F(val) { this.key = val; }
var instance = new F("value")
alert(instance.key) // "value"
Run Code Online (Sandbox Code Playgroud)
您可以看到的差异是第一个版本只key向F函数对象添加了一个memeber ,而第二个版本key在每个创建的实例上初始化一个新成员.newF
当您通过调用一个函数new的实例对象是自动创建,并且可以通过进行扩充this关键字.每个构造函数this默认返回.
您还可以向函数添加公共方法prototype,它们将可用于所有实例.他们可以使用this关键字单独更改其"状态"(如您所说).
function F(val) { this.state = val; } // unique
F.prototype.change = function() { this.state = "stuff"; }
var inst = new F("value")
var inst2 = new F("value")
alert(inst.state) // "value"
alert(inst2.state) // "value"
inst.change();
alert(inst.state) // "stuff"
alert(inst2.state) // "value"
Run Code Online (Sandbox Code Playgroud)
jQuery的
我甚至可以告诉你jQuery在幕后做了什么,但我认为你真的不想知道.:)
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// ...
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// ...
},
// ...
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
Run Code Online (Sandbox Code Playgroud)
所以基本上$(selector)意味着,它只是一个更容易键入的快捷方式(并且还可以防止注释中提到的"bug",其中fogetting 绑定 到全局对象,而不是当前实例).newjQuery.fn.init(selector)newthis
另外,所谓的插件添加为jQuery.fn.ext映射到jQuery.fn.init.prototype最后一行,你可以看到,这是另一个快捷方式.因此,当您调用$(selector)添加到的所有内容jQuery.fn时也将打开jQuery.fn.init.prototype,因此新实例将具有这些方法$(selector).ext(...).
// as you use it today
jQuery.fn.plugin = function ( ... ) { ... }
$(selector).plugin( ... )
// as it would be without shortcuts
jQuery.fn.init.prototype.plugin = function ( ... ) { ... }
(new jQuery.fn.init(selector)).plugin( ... )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
475 次 |
| 最近记录: |