我正在努力在包装器内构建一组原型辅助方法。但是为了便于使用,我希望能够在同一个调用下将该对象作为新实例和单个全局实例调用。
例如,使用 jQuery,您可以同时调用“$”和“$()”,它们的使用方式不同http://learn.jquery.com/using-jquery-core/dollar-object-vs-function/:
因此,鉴于下面的简单示例,我该如何做类似的事情?
(function () {
var myWrapper = function (foo) {
return new helper(foo);
};
var helper = function (foo) {
this[0] = foo;
return this;
}
helper.prototype = {
putVar: function(foo) {
this[0] = foo;
}
}
if(!window.$) {
window.$ = myWrapper;
}
})();
// create an new instace;
var instance = $("bar");
console.log(instance);
// call a prototype method
instance.putVar("foo");
console.log(instance);
// call a prototype method using the same call without new instance
// this doesnt work :(
$.putVar("foo");
// however this will work
window.myLib = $("foo");
myLib.putVar("bar");