如何在构造函数中同时使用原型和非原型对象字面量?

3
下面是一个示例脚本,说明我对JavaScript的字面量和原型行为有些不理解。是否可以像在原型方法中看到的那样(例如editor.prototype.inject(),editor.prototype.selection()等),将下面列出的辅助函数(即editor.document(),editor.fragment()等)放在对象字面值中?我找不到一种将辅助函数放置在对象字面值中而不覆盖构造函数的方法。
我知道我可以将整个脚本封装在函数内部,但我的目标是不使辅助函数成为私有的,我只想让它们被命名空间化,但仍可在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() {}, 

    // ...
};

1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - Bergi
1个回答

2
function editor(){ /*...*/ }

Object.assign(editor, {
  document(){//this is a new shortform for methods ;)
    //whatever
  }
  //...
});

问题在于,每当你将一个对象文字分配给editor时,都会覆盖该函数:
editor = {...};

由于没有办法构建具有属性的函数,我们需要先创建一个函数,然后再将我们的属性分配给它(就像我上面所做的那样)。


很遗憾,Object.assign似乎只有有限的IE支持。尽管如此,我现在理解了问题和解决方案(Object.assign,jQuery.extend等)。干杯! - Tell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接