Difference between creating javascript objects -
when creating object utilize js in oo manner, there difference within js engine between (with exception of beingness able define constructor:
var uploader = uploader || {};
and
var uploader = function() { }
and
function uploader() { }
especially when later, wish along lines of
uploader.dom = { create: function(file) { } };
is downwards personal preference? or there real difference?
objects:
var myobj = { myarr: [1,2,3], find: function(/*some arguments*/) { //some logic finds in this.myarr } }
in myobj.find
function this
keyword point myobj
(which resembles how this
works in languages have classes). can utilize functionality mix-ins:
var myobj2 = { myarr: [4,2,6] } myobj2.find = myobj.find;
in myobj2.find
function this
keyword point myobj2
.
also objects back upwards getters , setters (works on ie9+ , browsers):
var myobj = { myarr: [1,2,3], find: function(/*some arguments*/) { //some logic finds in this.myarr }, maxvalue() { homecoming math.max.apply(null, this.myarr);// maxvalue calculated on fly }, a_: null, () { homecoming this.a_; }, set (val) { //fire alter event, input validation this.a_ = val; } }
now max value in array can accessed this: myobj.maxvalue
. added property a_
. can't named same getter , setter appended underscore. appending or prepending underscores naming convention private variables should not accessed directly.
var qwe = myobj.a // a_ myobj.a = 'something'; //set a_
functions:
var u = new uploader(); // throw exception var uploader = function() { }
uploader defined in runtime here. not exist yet when seek instantiate it.
var u = new uploader(); //will work function uploader() {}
uploader defined in compilation time here work.
functions can used revealing pattern conceal members. functions don't back upwards getters , setters can set objects within functions.
function myfunc() { function privatefunc() {}; function publicfunc() {}; var obj = { //members, getters, setters }; homecoming { publicfunc: publicfunc, obj: obj } }
you can phone call mufunc.publicfunc()
outside of myfunc
because returned. can not utilize privatefunc
outside because not returned. revealing pattern functions not meant instantiated usually. because when instantiate within copied new instance. utilize more memory if add together functions using prototype
.
myfunc.prototype.somefunc = function() {};
like instances of myfunc
share same instance of somefunc
.
conclusion: functions can simulate private
access modifier in objects this
keyword acts similar of you'd expect in language have classes. can utilize call
, apply
, bind
alter context (i.e. 'this' keyword be) of function.
javascript
No comments:
Post a Comment