1

Lets say I have this function:

function myFunc () {
    this.property1 = 10;
}
var myObject = new myFunc();

Now lets say I want to add a new property to it.

myFunc.newProperty = "New"; 
myObject.newProperty = "New";
myFunc.prototype.newProperty = "New";

What is difference between these aproaches? And which one should I use?

3 Answers 3

3

Approach 1

myFunc.newProperty = "New"; 

Because the function itself is an object, you just create a new property on it. It may be useful you if you work directly with the Function object.

Approach 2

myObject.newProperty = "New";

On a new instance of the myFunc constructor, you create an own property. Useful when you need to modify a single instance, but don't want to modify the class itself with newProperty.
Any new instances created with new myFunc() will not inherit or contain the newProperty.

Approach 3

myFunc.prototype.newProperty = "New";

If you modify the constructor prototype, then the created objects will inherit this property. Useful when you need any existing or new object created with new myFunc() to inherit the newProperty.

Which one to use depends on the task. The points 2 and 3 are commonly used.

Sign up to request clarification or add additional context in comments.

1 Comment

good answer. Just a point with Approach 3 - what I inferred from the answer is that only new objects will inherit any property added to the constructor prototype, but in fact existing objects will also inherit the property too - it may be my misinterpreting your answer, but I just wanted to point that out
1

So when you are doing

myFunc.newProperty = "New"; 

this property is is treated as private Property of myFunc so even if you make some instance of myFunc you will not able to access.

Same in the case of

myObject.newProperty = "New";

when you are making it its treated a private property of myObject so outside of myObject you can not access it.

And when you are doing

myFunc.prototype.newProperty = "New";

You can access newProperty from all the instance of myFunc.

Which is good which is bad i cant say its all requirement

Comments

1

myFunct is Constructor function(in fact every function in JS can be used as Constructor), when used with new this function creates a new object.

now you want to add new properties to object:

1) want to add new property to already created myObject

myObject.newProperty = "New";

2) want to add new property to every object created from myFunc

function myFunc () {
    this.property1 = 10;
    this.newProperty = "New"; 
}

3) want to have new property in all the object already created from myFunc and it should be a property of parent object(so that only one copy is available) for all the newly created object from myFunc

myFunc.prototype.newProperty = "New";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.