The dynamic problem of JS prototype--the difference between using primitive prototype grammar and simple prototype grammar

Source: Internet
Author: User

For the rewrite of prototype prototype objects, we can use the following two ways:

    1. Add the attributes you want to add to the prototype object using the most primitive syntax
function= "Tom"="Doctor"; Person.prototype.sayname=function() {    alert (this. name);} var New Person (); Person1.sayname (); // Tom

2. Use a simple prototype syntax to encapsulate the added attributes in a literal context

function= {    "    Tom",    "Doctor",      function() {        alert (this. Name);    }} var New Person ();p erson2.sayname ();     // Tom

Although both are available, there is a difference when you encounter a prototype rewrite.

1. The first method:

 

function Person () {} var New Person ();     // instantiation of Person.prototype.name = "Tom"="Doctor"; Person.prototype.sayname=function() {        alert (this. name);         // Tom}

2. The second method:

function Person () {    }    varnew person ();     = {        "Tom"        ,        "Doctor"        ,function( {            alert (this. Name);        }    }    Friend.sayname ();         // error, no Sayname method found

The principle is as follows:

At this point, the overridden prototype object disconnects the existing prototype from any previously existing object instance, and its references are considered to be original prototypes, and there is no Sayname () method in the original prototype, and the stock error.

The dynamic problem of the

JS prototype--the difference between using primitive prototype syntax and simple prototype syntax

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.