Object.prototype object, which is a property of the global
Note: For you to run this code, open an empty tab in any of the browser that has developer tools and paste this code in the console.
The prototype is a dynamic relationship. If you add any of the properties to the
Object.prototype at anytime, it will reflect in the objects below the prototype chain.
Creating an Object without Prototype link
You can create object without this prototype linkage by using the
Object.create(objectParam) method. The parameter for this function must be the object that you wish should be the prototype of the new object. If
null is passed, there is no prototype link created.
Object.prototype.website = "codedodle"; Object.prototype.author = "Tamil Selvan"; // This object is created without the prototype inheritance. var newPost = Object.create(null); console.log(newPost); // The following will print “undefined” console.log(newPost.website);
If we add or try to update a property that is already in its prototype, it will become new property of that object instead of updating in its prototype object. You can never update a property in the prototype of an object, you can only retrieve it.
// Add properties to the prototype Object.prototype.website = "codedodle.com"; Object.prototype.author = "Tamil Selvan"; // Create an object with the Object.prototype as its prototype var PostTemplate = Object.create(Object.prototype); // dateCreated will be the same for all the object the has this object as the prototype PostTemplate.dateCreated = new Date(); document.writeln('Website of PostTemplate - ' + PostTemplate.website + '<br/>'); var OOPInJSPartOne = Object.create(PostTemplate); OOPInJSPartOne.title = 'Object Oriented Programming in Part One'; document.writeln('Title - ' + OOPInJSPartOne.title + '<br/>'); document.writeln('Website Property of OOPInJSPartOne - ' + OOPInJSPartOne.website); var OOPInJSPartTwo = Object.create(PostTemplate); OOPInJSPartTwo.title = 'Object Oriented Programming in Part Two'; // This will not updated in the prototype chain, it will be created as a property of this object OOPInJSPartTwo.website = 'someother.com'; document.writeln('Updated the website of OOPInJSPartTwo' + '<br/>'); document.writeln('Website in the Object.prototype - ' + Object.prototype.website + '<br/>'); document.writeln('Website in the PostTemplate - ' + PostTemplate.website + '<br/>'); document.writeln('Title - ' + OOPInJSPartTwo.title + '<br/>'); document.writeln('Website Property of OOPInJSPartTwo - ' + OOPInJSPartTwo.website + '<br/>');
Prototype in Native Types
You can also add properties to the Function, Boolean and other types prototype object. If you have something to add or something to ask, leave a comment.