JS Rewrite prototype object

Source: Internet
Author: User

First look at two very similar codes:

1.

function Person () {}         = {        Constructor:person,        name:"Nic", age        :"$",        sayname:function  () {            alert (this. Name)        }    };     var New Person ();    // examples are here         friend1.sayname ();

2.

function Person () {}     var New Person ();    // examples are here    Person.prototype = {        "Aty",        sayname:function() {            alert (  This . Name);        }    ;    Friend2.sayname ();

Two examples are rewriting prototype objects, but the order in which the instances are created directly results in two outputs.

The first one pops up "Nic", and the second one will error "TypeError:friend2.sayName is nota function" !!!

The only difference between the two ends of the code is whether the instance precedes or follows the prototype object rewrite.

The first paragraph overrides and then creates the instance, at which point the instance points to the rewritten prototype object, so it can be called to Sayname () in the prototype.

The second paragraph is then rewritten after the instance is created, and the instance points to the first prototype object. Overriding the prototype object erases all the properties and methods of the previous prototype object, so the instance does not access the Sayname ().

Also read "JavaScript Advanced Programming (3rd Edition)" in 156 pages and 157 pages, respectively:

"The pointer in the instance points to the prototype only, not to the constructor."

"Overriding the prototype object cuts off the relationship between the existing prototype and any previously existing object instances, which are still referred to as the original prototype."

JS Rewrite prototype object

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.