Object Prototype
Prototype is something all javascript object have.
The prototype is used for property resolution.
It is used when trying to define a property that is not directly defined on an object.
Example 1:
var person = {
name: "notset",
sayHi: function(){
console.log("hello from" + this.name);
}
}
//Lets say we wanted to create a manager:
var manager = {};
manager.__proto__ = person;
manager.sayHi(); -> "hello from notset" //Even though the manager object didn't have a sayHi() function, we can access the sayHi function.
manager.name = "Bossman";
manager.sayHi(); -> "hello from Bossman"
//Which is basically equivalent to:
var manager2 = {
name: "Bossman"
sayHi: person.sayHi
}
//Even object prototype has object.
//Every object but the object prototype itself has a prototype.
manager._proto
//We can check if the object has a property:
manager.hasOwnProptery("sayHi"); -> false
manager.__proto__hasOwnProptery("sayHi"); -> true
//If we want to say manager.sayHi(), it goes through those setps:
1. manager.hasOwnProptery("sayHi"); -> false
2. manager.__proto__hasOwnProptery("sayHi"); -> true
3. manager.__proto_.sayHi.call(manager);
Example 2:
var dummy = "";
dummy.__proto__.sayHi = function() { //Now all string in js has that function
console.log(this + "hello");
}
var manager = {};
manager.__proto__ = person;
manager.sayHi(); -> Say hi
manager.sayHi = undefined; //Please not this does not unset the property
manager.sayHi(); -> Uncaught TypeError, manager.sayHi is not a value
manager.hasOwnProperty("sayHi") -> true //Even though its undefined
//How to remove a property, we need to use 'delete':
delete manager.sayHi
manager.hasOwnProperty("sayHi") -> false