Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The most simple way to do what you want would be (I think):</p> <pre><code>$ = function(){ if (!(this instanceof $)){ return new $; } this.name = 'levi'; return this; } </code></pre> <p>The fact that just returning <code>this</code> doesn't create an instance of $ is because of the way <code>this</code> is created executing <code>$</code> as a regular function: in that case the value of <code>this</code> points to the global object (within a browser: <code>window</code>, actually calling executing <code>$()</code> is the same as <code>window.$()</code>). It's a fact of javascript life so to speak. The fact that <code>console.log(new $().name)</code> shows the right value is because you call the function as a constructor, which returns an instance of that constructor (i.e. an new instance of <code>$</code>). But <code>console.log($().name)</code> will also print 'levi', because it returns the global object with property <code>name</code>, i.e. <code>window.name</code>. try <code>$(); console.log(name)</code> and you'll see <code>name</code> is a global variable now. So if you don't want to use the <code>new</code> keyword every time, check if your function is called as a regular function, or as a constructor for an instance (<code>=== instanceof $</code>) within the constructor function. With the above method an instances constructor, no matter if it's instantiated with or without <code>new</code> will allways be <code>$</code></p> <p>Maybe you should rephrase the title of your question to: 'An Object [constructor] that returns <em>an instance of itself</em>'</p> <p>Maybe <a href="http://blog.tuenti.com/dev/functions-and-execution-contexts-in-javascript-2/" rel="nofollow">this blog entry</a> can shed extra light.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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