Javascript函数类似于对象,即“$”。可以用作例如$()以及一个对象$ [英] Javascript Function like Objects i.e. "$" can be used as a function e.g. $() as well as an object $
本文介绍了Javascript函数类似于对象,即“$”。可以用作例如$()以及一个对象$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标题中的问题。我一直想知道并且未能从jQuery源代码中找到答案。如何做到这一点。
Questions in the title. I've always wondered and failed to find out from the jQuery source. How this is done.
重申一下。在jQuery中:$如何成为一个函数,例如$()以及一个对象$。
To reiterate. In jQuery: how does the "$" become a function e.g."$()" as well as an object "$."
我可以单向创建它或者其他如此......
I can create it one way OR the other like so...
var $ = function(){
return {each:function(){console.log("Word")}}
}
// $.each(); FAIL!
$().each(); // Word
var $ = {
each:function(){console.log("Word")}
}
$.each(); // Word
//$().each(); FAIL!
推荐答案
从基本功能开始:
var $ = function(expr) { return $.select(expr); }
然后,为其添加额外的功能:
Then, add extra functionality to it:
$.select = function(expr)
{
console.log("selecting " + expr);
return $; // TODO: perform selection
};
$.each = function()
{
console.log("Called $.each()");
};
你可以通过查看来源:
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 ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// contents of init() here
}
}
这篇关于Javascript函数类似于对象,即“$”。可以用作例如$()以及一个对象$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文