javascript - A library with close can't create a new obj base on its constructor -
i received error of uncaught typeerror: object not function
on line new
can run if var item = mylib;
however, not clear issue here.
(function(window){ function mylib (){ var library={}; library.localvar1="one"; library.localvar2="two"; library.func1 = function (){ console.log("func1 output"+library.localvar1) return true; } library.func2 = function (){ library.func2var1 = "func2one"; console.log("func2 output"+library.localvar2) return library.func2var1; } return library; } //define globally if doesn't exist if(typeof(library) === 'undefined'){ window.mylib = mylib(); } else{ console.log("library defined."); } })(window); var item = new window.mylib; console.log(item.localvar2,"var2"); console.log(item.func2(),"func2"); console.log(item.func1(),"func1");
as use var item = new window.mylib;
assume want create new instance library
.
but in code, library
object
, not constructor, constructor should function
. you'll error.
(function(window){ function mylib (){ var library = function() { // set self's variable this.localvar1="one"; this.localvar2="two"; } // use prototype define shared function. library.prototype.func1 = function (){ console.log("func1 output"+this.localvar1) return true; }; library.prototype.func2 = function (){ library.func2var1 = "func2one"; console.log("func2 output"+this.localvar2) return library.func2var1; }; return library; } //define globally if doesn't exist if(typeof(library) === 'undefined'){ window.mylib = mylib(); } else{ console.log("library defined."); } })(window); var item = new window.mylib(); // create instance of library console.log(item.localvar2,"var2"); console.log(item.func2(),"func2"); console.log(item.func1(),"func1");
Comments
Post a Comment