javascript - What's the difference between "function x.y()" and "x.y = function ()"? -



javascript - What's the difference between "function x.y()" and "x.y = function ()"? -

the difference between these 2 pieces of code in line 1 in both blockquotes.

why these 2 pieces of code behave different?

function cat.meow() { console.log("meow"); };

versus

cat.meow = function () { console.log("meow"); };

the first 1 invalid javascript, sec improve idea, more details in following...

why?

variable / function names can have letters, underscores, $, numbers (if they're not first character) along few other acii, , unicode characters (check here or here recommended kaiido , felix king). same var cat.meow; invalid javascript , throw error. more specifically

syntaxerror: unexpected token '.'.

the compiler expecting parenthesis or space sees period not assuming object. happens bracket syntax object :( means can't define function object 'item' first way

explanation

when do: foo = function () {} set value of foo function. when function function foo () {} 'creates' foo.

so...

the sec 1 referring meow in cat. setting meow in cat function valid. equivalent this:

var cat = { meow: function () { console.log("meow!"); } };

obviously cat isn't defined, still throw error. if really want have function called cat.meow (i advise against it), following

window['cat.meow'] = function () { console.log("meow"); };

this clutters global scope unless have different object , extremely bad practice; if utilize it, in secret otherwise every programmer bashing on coding practices.

javascript

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -