【发布时间】:2010-06-02 23:51:04
【问题描述】:
所以我正在使用这个非常标准的 jquery 插件模式,您可以在将 jquery 函数应用于特定实例后获取 api。
这个 API 本质上是一个带有一堆方法和数据的 javascript 对象。
所以我想为对象创建一些私有内部方法,仅用于操作数据等,而这些方法不需要作为 API 的一部分提供。
所以我尝试了这个:
// API returned with new $.TranslationUI(options, container)
$.TranslationUI = function (options, container) {
// private function?
function monkey(){
console.log("blah blah blah");
}
// extend the default settings with the options object passed
this.settings = $.extend({},$.TranslationUI.defaultSettings,options);
// set a reference for the container dom element
this.container = container;
// call the init function
this.init();
};
我遇到的问题是 init 无法调用该函数“monkey”。我不明白为什么它不能背后的解释。是不是因为init是一个原型方法?($.TranslationUI的原型在代码的其他地方扩展了一堆包括init在内的方法)
$.extend($.TranslationUI, {
prototype: {
init : function(){
// doesn't work
monkey();
// editing flag
this.editing = false;
// init event delegates here for
// languagepicker
$(this.settings.languageSelector, this.container).bind("click", {self: this}, this.selectLanguage);
}
}
});
任何解释都会有所帮助。也会喜欢使用此模型创建私有方法的其他想法。
这些特定的功能不必在原型中,我也不需要保护私有方法不被外部使用,但我想知道我将来应该如何满足这个要求。
// 根据 Matthew 的评论编辑 所以我尝试根据 Matthew 的评论移动原型定义。这似乎现在可以工作,但仍然不确定这是否是正确的方法。想法?显然,如果我将原型对象移动到单独的区域中会更干净
$.TranslationUI = function (options, container) {
function monkey(){
console.log("blah blah blah");
}
// extend the default settings with the options object passed
this.settings = $.extend({},$.TranslationUI.defaultSettings,options);
// set a reference for the container dom element
this.container = container;
$.extend($.TranslationUI.prototype,
{
init : function(){
monkey();
// editing flag
this.editing = false;
// init event delegates here for
// languagepicker
$(this.settings.languageSelector, this.container).bind("click", {self: this}, this.selectLanguage);
}
}
);
// call the init function
this.init();
};
因此,虽然这可行,但糟糕的是每次构造函数运行时我都在重新初始化原型。我敢肯定这不是有效的。但不确定如何让原型方法访问某个实例的私有函数/变量。
【问题讨论】:
标签: javascript jquery