The concept of prototype in JavaScript is very confusing, especially to those who come with a C++/JAVA/... background. As an OOP langauge, JavaScript is very different from the languages with class. Its classless feature make it somehow difficult to understand. To muddy the water, JavaScript uses prototype-based inheritance but the prototype property of an object is not really its prototype. javascript
As a beginner, I read many articles and do some experiments to tidy up the mess of prototype. Here I would like to share what I have learnt with you. Most of the findings I get is experiment based so you can evaluate them by typing simple statements in the editor you use!java
As Linus said, "Talk is cheap. Show me the code." Let me show you the demonstration code below. To begin, we have:express
function abc() { // nothing } var x = new abc();
x.__proto__ === abc.prototype; // abc.prototype is used to build x x.constructor === abc; // not really, see (1) typeof x.prototype === "undefined"; // cannot be used to build new object
typeof abc === "function"; abc.__proto__ === Function.prototype; abc.constructor === Function; // not really, see (1) typeof abc.prototype === "object";
abc.prototype.constructor === abc; x.hasOwnProperty('constructor') === false; abc.prototype.hasOwnProperty('constructor') === true;
abc.prototype = {}; // abc.prototype becomes a new empty object x instanceof abc === false; // x is no longer an instance of abc, see (3) x.constructor === abc; // constructor property is still abc, why? x.__proto__ !== abc.prototype; // because __proto__ points at the old abc.prototype x = new abc(); // reassign new abc() to x x instanceof abc === true; // x is an instance of abc again, see (3) x.__proto__ === abc.prototype; // same now abc.prototype.hasOwnProperty('constructor'); // the empty object does not has its own constructor abc.prototype.__proto__.constructor === Object // the constructor of Object.prototype is used x.constructor === Object; // x.__proto__.__proto__.constructor is accessed
abc.prototype.__proto__ === Object.prototype; abc.prototype instanceof Object === true; x.__proto__ === abc.prototype; x instanceof abc === true; x.__proto__.__proto__ === Object.prototype; x instanceof Object === true;
abc.prototype.color = "red"; x.color === "red"; // abc.prototype.color is accessed Object.prototype.food = "potato"; x.food === "potato"; // Object.prototype.food is accessed abc.prototype.food = "apple"; // now abc.prototype also has food property x.food === "apple"; // food property in abc.prototype is accessed instead Object.prototype.food === "potato"; // food property in Object.prototype remains unchanged
Do you find it interesting? If yes, please tell me so that I will write more on this topic in the future!app
版權聲明:本文博主原創文章,博客,未經贊成不得轉載。less