Note that there are some explanatory texts on larger screens.

plurals
  1. POAn Object that returns an instance of itself
    primarykey
    data
    text
    <p><strong>Background:</strong> My latest project cannot use a large library, which saddens me. There are a few things that I would like to have from any library such as the missing functions <code>addClass</code>, <code>hasClass</code>, <code>removeClass</code>, compatible <code>addEventListener</code>, etc. So I created <a href="http://jsfiddle.net/morrison/tL3Xg/" rel="noreferrer">a little object</a> which I'd like some opinions on some other time, but I'm having a little bit of trouble setting it up how I'd like.</p> <p>For convenience of use, <strong>I want an object to return a new instance of itself on creation.</strong></p> <p>Given:</p> <pre><code> $ = function() { this.name = "levi"; return this; }; console.log($()); </code></pre> <p>We get DOMWindow instead of <code>$</code> because of the quirky nature of <code>this</code> in JavaScript. <em>What's more strange to me is that <code>console.log(new $().name)</code> properly returns "levi". If <code>this</code> is bound to window, why did the object properly get the value?</em>. We could just add new <code>console.log(new $())</code> and it works. However, I don't want to write new everytime. So I tried:</p> <pre><code>$ = function() { var obj = function() { this.name = "levi"; }; return new obj(); }; console.log($()); </code></pre> <p>Which gives me what I want, but it seems a bit unnecessary to wrap the object inside of a function which creates it. Further more, the returned object is <code>obj</code> and not <code>$</code>. Comparison tests would fail.</p> <p><strong>What are some other ways this can be done?</strong> Is there a more elegant solution? I have no qualms about rethinking my entire process. I consider myself pretty good at using JavaScript, but creating new JavaScript is something I am very new to.</p> <hr> <p><strong>Edit:</strong> Does anyone see anything wrong with the following solution:</p> <pre><code>$a = function() {}; $ = function() { if (!(this instanceof $)) { return new $(); } this.name = "levi"; return this; }; //helper function var log = function(message) { document.write((message ? message : '') + "&lt;br/&gt;"); }; log("$().name == window.name: " + ($().name == window.name)); //false log("$().name: " + $().name); //levi log("window.name: " + window.name); //result log(); log("$a instanceof $: " + ($a instanceof $)); //false log("typeof $a: " + (typeof $a)); //function log("typeof $: " + (typeof $)); //function </code></pre> <p>It appears to be working in all my tests. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    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