Today, when I checked Javascript Object-Oriented Programming articles on the Internet, I saw an example that made me subconsciously judge the error. Although the principle is very simple, I recorded it, for future work and query by a large number of Javascript learners.
<script type="text/javascript">function A(){this.a="a";}A.prototype.b="b";A.prototype.getA=function(){return this.a;}function B(){this.c="c";}B.prototype=new A();B.prototype.constructor=B;var b=new B();var a=new A();console.log(b.constructor==B);console.log(a.constructor==B);console.log(b instanceof B);console.log(b instanceof A);console.log(b instanceof Object);</script>
The above is a piece of code written by myself. The specific problem is to write the console. log value, where my subconscious judgment:
console.log(a.constructor==B); //true
The reason is that B. prototype. contructor overwrites the contructor attribute of the. prototype object and runs the above Code:
The running result proves that my judgment is incorrect, B. prototype. contructor has not rewritten. the contructor attribute of the prototype object is B. the contructor attribute is added to the prototype object (that is, the instantiated object. In general, I made a low-level error:
Although the values stored in the prototype can be accessed through the object instance, the values in the prototype cannot be overwritten through the object instance. If we add an attribute to the instance and it has the same name as the property in the instance prototype, we will create this attribute in the instance, which will shield the property in the prototype. You can use the delete operator to completely delete instance properties, but not properties in the prototype. Therefore, the attributes in the prototype are read-only for instance objects.