【发布时间】:2015-04-15 07:53:56
【问题描述】:
我正致力于在一个包装器中构建一组原型辅助方法。但是为了便于使用,我希望能够在同一个调用下将该对象作为新实例和单个全局实例调用。
例如,使用 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");
【问题讨论】:
标签: javascript object window global-namespace