javascript - If there is no distinction between classes and objects why doesn't this code work? -


i taught in javascript there no distinction between objects , classes. can explain why code generate error:

var firstobj = function() {};  firstobj.prototype.sayhi = function() { document.write("hi!"); };  firstobj.sayhi(); 

whereas 1 works:

var firstobj = function() {};  firstobj.prototype.sayhi = function() { document.write("hi!"); };  new firstobj().sayhi(); 

what's difference? why isn't first 1 working?

the key issue here firstobj variable function object, not firstobj object. subtle distinction, type of object determines prototype inherits.

the prototype template applied newly created objects of particular type. must create firstobj object (usually new invokes constructor , assigns prototype) in order have template applied it. in first example, firstobj variable function object, not firstobj object has prototype of function not of else..

in second example, create firstobj object inherits prototype type of object.

if want method applied in first example works on function object you've created, put method directly on existing function object, not on prototype.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -