Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: what are some guidelines on how to define new data types?
    primarykey
    data
    text
    <p>Suppose you are creating the data type and expose its behavior. </p> <p>Can you give some examples of when would you use:</p> <ul> <li><p>a function &amp; new:</p> <pre><code>// define new data type var CustomDataType= function(){ this.a='whatever'; this.doX= function(){/*some code*/}; } // create a new instance of our custom data type var obj= new customDataType(); </code></pre></li> <li><p>an object literal &amp; Object.create:</p> <pre><code>// define new data type var customDataType = { a: 'whatever', doX: function(){/*some code*/} } // create a new instance of our custom data type var obj= Object.create(customDataType); </code></pre></li> <li><p>a function that builds your object:</p> <pre><code>function customDataTypeFactory(options){ return { a: 'whatever', doX: function(){/*some code*/} } }; // create a new instance of our custom data type var obj= customDataTypeFactory(options); </code></pre></li> </ul> <p>I feel this could be labeled duplicate for: <code>new</code> vs <code>Object.create</code> but my main interest is not in discussing which one is better but rather to know if there are specific use cases where one should be preferred over the others.</p> <p>I have read many posts on related questions and the book from Crockford: Javascript: the good parts. So far I have concluded that it is a matter of preference, tough the advice from Crockford resonates a lot with me to me: "try to avoid the features that are dangerous and unnecessary"... I'm talking about <code>new</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload