11

I basically having hard times understanding why I cannot overwrite an object property when using inheritance from another object, it goes like this.

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
};

Object.defineProperties(Person.prototype, {
  sayHi : {
   value :function() {
     return "Hi there";
   },
   enumerable : true,
   writable : true
  },
 fullName : {
   get : function() {
    return this.firstName + " " + this.lastName;  
   },
   enumerable : true
  }                      
});


var createEmployee = function(firstName, lastName, ocupation) {
  var employee = new Person(firstName, lastName);
  employee.ocupation = ocupation;  

 Object.defineProperty(employee, "sayHi", {
   sayHi : {
    value : function() {
     return "Hey I am " + this.firstName;
    }
   }
 });

 return employee;
};

var janeDoe = createEmployee('Jane', 'Doe', 'Actress');

So, accoding to what I understand, I should overwrite the sayHi property on the employee object, however, I get it as undefined.

Could please some1 show me money?

here is the jsfiddle

Best Regards.

3 Answers 3

30

You could use the outdated Object.defineProperty() or the Object.assign(). However, there's a cleaner, more modern solution to this.

Simply do:

objectName = {...objectName, property: "newvalue"};
// or
objectName = {property: "newvalue", ...objectName};

the difference between the two is that the first will overwrite the property named property, while the second will create a new property called property and assign a value, however, it won't overwrite it if it already exists.

Take a look at JS spread syntax for more info.

Such could also be done for setting your prototype:

Person.prototype = {...Person.prototype, sayHi: _=>"Hi there!"};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank u! But this answer came like 5 years later... where were u when i needed u? Ah?? :@
lol! This stuff is relatively new... So even if I had seen this sooner it'd likely not have been as easy as it is now... Anyways, I hope it helps in the future!
6

Just realized the answer I gave was bad.

You don't need the name inside the object there.

Object.defineProperty(employee, "sayHi", {
sayHi : {//<- don't need this.
    value : function() {
    return "Hey I am " + this.firstName;
  }
 }//<- or this.
});

Comments

0

Try this:

 Object.defineProperty(employee, "sayHi", {
   value: "Hey I am " + employee.firstName
 });

Also, Mozilla's explanation on Object.defineProperty() is quite excellent, you should check it out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.