Tell
Tell

Reputation: 316

How to have both prototype and non-prototype object literals alongside constructor function?

The following is an an example script illustrating a problem I'm having understanding JavaScript's literal and prototyping behaviours. Is there a way to place the helper functions listed below (i.e. editor.document(), editor.fragment(), etc.) in an object literal like you see me doing with the prototype methods (i.e. editor.prototype.inject(), editor.prototype.selection(), etc.). I can't find a way to place helper functions inside an object literal without overwriting the constructor function.

I know I can encapsulate the entire script inside a function, but my goal is to not make the helper functions private, I simply want them to be namespaced but still accessible in the same scopes that the editor() constructor function is.

The only thing I can assume is either this isn't possible, or I'm misunderstanding something about JavaScript's object literals (does non-prototype literals equate to an automatically-created instance of said literal?)...

/**
 * 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() {}, 

    // ...
};

Upvotes: 3

Views: 91

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

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

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

The problem is that whenever you assign an object literal to editor, you will override the function:

editor = {...};

As there is no way to construct a function with properties, we need to create a function first and then assign our properties to it ( like i did above).

Upvotes: 2

Related Questions