Is the property on the prototype overriding the property of the actual object?

I have a Person constructor function similar to sayHello method

 var Person = function(firstName,lastName) { this.lastName = lastName; this.sayHello = function() { return "Hi there " + firstName; } }; 

Then I define a different version of the sayHello method on the Person prototype:

 Object.defineProperties(Person.prototype,{ sayHello: { value: function() { return 'Hi there'; }, enumerable: true } }); 

Now, if I create an instance of Person and call sayHello on it, I notice that it uses the version of sayHello that is defined on the prototype.

 var JoeBlow = new Person('Joe','Blow'); > JoeBlow.sayHello() < "Hi there" // I was expecting "Hi there Joe" 

It bothers me.

Why doesn't the JoeBlow object use its own sayHello implementation, instead of looking for sayHello on its prototype?

+6
source share
1 answer

By default, properties defined with defineProperties are read-only.

See MDN

writable - true if and only if the value associated with this property can be changed using the assignment operator. Lying.

Unfortunately, when you try to set the read-only property in the old JS style, it fails rather than throwing an exception, so it is very difficult to debug.

If you did this in strict mode , you would get:

TypeError: cannot only assign the read only "sayHello" property of an object [object Object]

You can explicitly define a property for the record.

 Object.defineProperties(Person.prototype,{ sayHello: { value: function() { return 'Hi there'; }, enumerable: true, writable: true } }); 

Then this.sayHello = function() { will not work quietly, and you will successfully mask the version of the property living on the prototype.

+6
source

All Articles