javascript - Adding properties to function, object and prototype -


lets have function:

function myfunc () {     this.property1 = 10; } var myobject = new myfunc(); 

now lets want add new property it.

myfunc.newproperty = "new";  myobject.newproperty = "new"; myfunc.prototype.newproperty = "new"; 

what difference between these aproaches? , 1 should use?

approach 1

myfunc.newproperty = "new";  

because function object, create new property on it. may useful if work directly function object.

approach 2

myobject.newproperty = "new"; 

on new instance of myfunc constructor, create own property. useful when need modify single instance, don't want modify class newproperty.
new instances created new myfunc() not inherit or contain newproperty.

approach 3

myfunc.prototype.newproperty = "new"; 

if modify constructor prototype, created objects inherit property. useful when need existing or new object created new myfunc() inherit newproperty.

which 1 use depends on task. points 2 , 3 commonly used.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -