Returning an object but not using the new keyword, Javascript? -


i trying create object gets returned without new keyword in javascript?

my code structure far;

mylib.func = (function() {      "use strict";      function func() {          this._init();     };      func.prototype._init = function() {          this.somevar = 5;     };      return func;  })(); 

this works when using new keyword;

new mylib.func(); 

how can make can do;

var func = mylib.func(); 

but still return object same first example?

what have tried

mylib.func = (function() {      "use strict";      function func() {          if (window === this) {             return new mylib.func();         } else {             this._init();         }     };      func.prototype._init = function() {          this.somevar = 5;     };      return func;  })(); 

this not work learned example on slide 25 of john resig's tips on building library, http://ejohn.org/blog/building-a-javascript-library/

i know there existing frameworks, rolling own make me learn alot, , can see isn't alot @ moment!

in strict mode, this undefined default. can account feature adding condition:

    if (window === || undefined === this) {         return new mylib.func();     } else {         this._init();     } 

or checking whether current object instance of constructor (using instanceof):

    if (this instanceof func) {         this._init();     } else {         return new func();     } 

(ps. you've got typo in code; javascript case-sensitive, should use return instead of return @ end)


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -