The idea of using prototypes is that when you try to access a property on an object the interpreter will first try to find that property on the given object.
If the property is not found on the given object then the interpreter will try to find it on the object's prototype and so on until the prototype chain ends in null
.
If the property is not found the interpreter returns undefined
. Otherwise it returns the property value.
In your case when you are accessing the property sex
it's not found on the object but it is found on the object's prototype. Hence it returns male
.
Then when you assign a new value to sex
it creates a new property on the given object instead of changing the property on the object's prototype because JavaScript is a dynamic language.
This is fine since the new value shadows the old value. That's the way prototypal inheritance works.
If you explicitly want to update the property on the prototype instead of the given object I suggest you create propeties on your objects as follows:
function defineProperty(object, name, value) {
Object.defineProperty(object, name, {
value: value,
writable: true,
enumerable: true
});
}
function extendObject(object) {
var extendedObject = Object.create(object);
Object.keys(object).forEach(function (key) {
Object.defineProperty(extendedObject, key, {
set: function (value) {
object[key] = value;
},
enumerable: true
});
});
return extendedObject;
}
var man = Object.create(null);
defineProperty(man, "sex", "male");
var yehuda = extendObject(man);
defineProperty(yehuda, "firstName", "Yehuda");
defineProperty(yehuda, "lastName", "Katz");
This should solve your problem. To know more about prototypal inheritance read this answer.
Edit: I suggest you do not try to change the values of the prototype. This is because many objects may have the same prototype. Changing any value on the prototype means that the change will be reflected on all the objects depending on it. Unless that is what you want to achieve I suggest you make do with shadowing properties on the prototypal chain.
Note: You can delete properties on objects. If the property you deleted was shadowing another property then it will shadowed property will be used the next time you access the same property name.