In javascript whats the difference when i create a variable in object like below 2 ways
user.name = 'hello';
user.prototype.name = 'hello';
In javascript whats the difference when i create a variable in object like below 2 ways
user.name = 'hello';
user.prototype.name = 'hello';
Fundamentally, there isn't any, in that in both cases you're creating or modifying a property on an object. But the effect of creating/modifying that property can be significant.
First, note that user
will only have a property called prototype
if it's a function* (or if you've created one on another kind of object). I'm going to assume that user
is a function for the remainder of this answer. And since we're using user
as a constructor, I'll use User
instead for the rest of this answer as the overwhelming convention in JavaScript is that the names of constructor functions start with an uppercase character.
User.prototype
is used if you create objects via new User
. In that case, the object that User.prototype
refers to will be used as the new object's prototype. That means that if you try to retrieve the value of a property on that new object and the object doesn't have a property with the given name, the JavaScript engine will look at the object's prototype to try to find it.
So adding or modifying a property on User.prototype
may seem to add it to objects you've created via new User
:
function User() {
}
var u1 = new User();
console.log(u1.name); // undefined
User.prototype.name = "hello";
console.log(u1.name); // "hello"
It hasn't actually been added to u1
, it's just that since u1
doesn't have its own name
property, when we look up name
on it, the property from its prototype is used instead.
To further understand the relationship between a function's prototype
property and the prototype of an object, see __proto__
VS. prototype in JavaScript.
* It needs to be a function created via the function
or class
keyword to have a prototype
property by default; arrow functions, async
functions, and methods don't have prototype
by default and cannot be used as constructor functions.
First scenario:
user.name = 'hello'
if you have created an object like this:
var user = { id:'abc'};
and then you do user.name = 'hello', will simply add a property to the user object as
user{name:'hello',id:'abc'}
Second scenario:
user.prototype.name = 'hello';
if you have created an object using constructor; eg;
function User(id) {
this.id = id;// creating an object which will differ in id;
}
now:
user.prototype.name ='hello';
will initialize any instance of user with the name as hello. We use prototype when we want the instances to have the same property and has only one copy in case of methods. eg
var newUser = new user('id');
now newUser will be -
newUser{id:'id',name:'hello'}