在JavaScript中同时作为函数的变量
我真的很想实现这样的东西在JavaScript中同时作为函数的变量,javascript,jquery,Javascript,Jquery,我真的很想实现这样的东西 myVar.myAnotherVar; myVar.myMethod(); myVar("sample text"); jQuery就是这样实现的 jQuery.fn; jQuery.ajax(); jQuery("#myBtn"); 如何实现像jQuery这样的东西,将所有内容保存在一个名称空间中?这和原型有关吗?如何使用变量同时作为函数调用 谢谢:)JavaScript中的函数是对象,您可以像任何其他对象一样任意向它们添加属性: function foo() {
myVar.myAnotherVar;
myVar.myMethod();
myVar("sample text");
jQuery就是这样实现的
jQuery.fn;
jQuery.ajax();
jQuery("#myBtn");
如何实现像jQuery这样的东西,将所有内容保存在一个名称空间中?这和原型有关吗?如何使用变量同时作为函数调用
谢谢:)JavaScript中的函数是对象,您可以像任何其他对象一样任意向它们添加属性:
function foo() {
// Code for when you call `foo` goes here
}
foo.someData = "bar";
foo.someFunction = function() {
// Code for when you call `foo.someFunction` goes here
};
jQuery所做的事情稍微复杂一些,但有点不同寻常,有两种方式:
jQuery
函数(通常别名为$
)只是对创建新对象的构造函数调用的包装。(构造函数名为init
)fn
的jQuery
函数的属性中添加了对init
函数的prototype
属性的引用。这两个属性(jQuery.fn
和init.prototype
)都引用了当您使用new init
时将成为实例原型的对象jQuery.prototype
中的同一个对象,尽管jQuery
没有用作构造函数。这样,$的$()实例将为true
var foo = function() {
// The public function
function foo(args, here) {
return new init(args, here);
}
// The hidden constructor function
function init(args, here) {
// ...do something with `this`, perhaps
}
// The object that becomes the prototype of instances created via `new init`
foo.fn = foo.prototype = init.prototype = {
// An instance-specific function, like jQuery's `css`
instanceMethod: function() {
// Has access to `this`
}
};
// A random piece of "static" (not instance-specific) data
foo.someData = "bar";
// A "static" (not instance-specific) function, like jQuery's `$.ajax`
foo.staticMethod = function() {
// Doesn't have (useful) access to `this`
};
return foo;
}();
@Mahan:最基本的是,是的。@Mahan:我添加了一个更复杂的例子来说明jQuery在上面所做的事情,希望这会有用。