What is the difference between adding a property to a function object vs, adding a property to the objects prototype. See code below.
var foo = function() { this.name = alert("test") };
foo.newProp = function() { ... };
var value = new foo();
// vs
foo.prototype.newProp = function() { ... }
var value = new foo();
My confusion is what happens to value when this code is run for each, AND how 'this' is affected.
Firstly, we know that functions are nothing but objects as we can attach properties to it. That is what is happening in the case1.
We are just simply attaching a property to a function Foo
Case 1
var Foo = function(){
this.name = "myname";
}
Foo.newProp = function(){};
The property attached to the function can be simply accessed as how we access properties of an object.
Case 2
In this case the same property is sitting on the prototype
of that function. When any object is created using this function Foo
, it will get access to this function by default.
When calling the function using that object, the context this
will know the object calling that function and this
points to the object calling it.
Foo.prototype.newProp = function(){ console.log("function on prototype");}
var value = new Foo();
console.log(value);
Also in case 2, since we are adding properties to the prototype of the function, they are not sitting on the object made using that function but on the proto of that object. Check this screenshot shown below:
That means there is a common memory location to which every object accessing that property will be pointing and hence it is memory efficient as well.
You can always go ahead and modify that property by overriding it by defining it directly on the object as:
value.newProp = function(){ console.log("modified property") };
Now, if you call this function, it will find it directly on the object and wont go down the prototype chain to access it from the common memory location i.e prototype of the function Foo