我有一个原型(prototype)函数,我想在有限的范围内使用它,以便为它提供一个 jquery 插件。
//Prototype
function StringBuilder(str) {
this.value = str;
}
StringBuilder.prototype.append = function (str) {
this.value = this.value + str;
return this;
};
//jQuery plugin with Revealing module pattern
jQuery.NameOfThePlugin = (function () {
//i would like to be able to use StringBuilder only in this scope
helloWorld = new StringBuilder('Hello');
helloWorld.append(' World');
})(window);
这可能吗?
谢谢
最佳答案
是的,只需包装您的代码in an IIFE这样您的 StringBuilder
仅在其范围内可用,而不是全局可用。然后 jQuery 插件向它导出一个闭包。
(function() {
function StringBuilder(str) {
this.value = str;
}
StringBuilder.prototype.append = function (str) {
this.value = this.value + str;
return this;
};
jQuery.NameOfThePlugin = function () {
var helloWorld = new StringBuilder('Hello');
helloWorld.append(' World');
…
}; // im pretty sure that plugin is supposed to be a function?
}());
您还可以在返回导出模块的地方使用实际的显示模块模式,在本例中为插件函数:
jQuery.NameOfThePlugin = (function() {
function StringBuilder(str) {
this.value = str;
}
StringBuilder.prototype.append = function (str) {
this.value = this.value + str;
return this;
};
return function () {
var helloWorld = new StringBuilder('Hello');
helloWorld.append(' World');
…
}; // im pretty sure that plugin is supposed to be a function?
}());
关于javascript - 有没有办法在有限范围内对命名空间进行原型(prototype)设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302817/