Thoughts on a basic example

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.