下面是一个示例脚本,说明我对JavaScript的字面量和原型行为有些不理解。是否可以像在原型方法中看到的那样(例如editor.prototype.inject(),editor.prototype.selection()等),将下面列出的辅助函数(即editor.document(),editor.fragment()等)放在对象字面值中?我找不到一种将辅助函数放置在对象字面值中而不覆盖构造函数的方法。
我知道我可以将整个脚本封装在函数内部,但我的目标是不使辅助函数成为私有的,我只想让它们被命名空间化,但仍可在editor()构造函数所在的相同作用域中访问。
唯一我能假设的是,要么这是不可能的,要么我对JavaScript的对象字面量有些误解(非原型字面量是否等同于自动创建的该字面量实例)...
我知道我可以将整个脚本封装在函数内部,但我的目标是不使辅助函数成为私有的,我只想让它们被命名空间化,但仍可在editor()构造函数所在的相同作用域中访问。
唯一我能假设的是,要么这是不可能的,要么我对JavaScript的对象字面量有些误解(非原型字面量是否等同于自动创建的该字面量实例)...
/**
* Editor's constructor.
*/
editor = function(config) {
// Setup object
this.config = config;
// ...
// Chainable
return this;
};
/**
* Helper functions that can be called directly without instantiating
* the "namespace" (i.e. editor) constructor. For readability, is it
* possible to put these in an object literal outside of prototype?
*/
editor.document = function() {};
editor.fragment = function() {};
editor.isHtml = function() {};
editor.isTag = function() {};
editor.toNodes = function() {};
/**
* Functions requiring an instance of editor. They can be placed in
* a pretty object literal that's easy to read... But what about the
* helper methods above that I just want as part of the editor
* namespace but not part of the instance? Why can't those be in an
* object literal? Am I missing something?
*/
editor.prototype = {
// ...
config : {},
inject : function() {},
selection : function() {},
// ...
};