Js: go deep into prototype (bottom: prototype rewriting)

Source: Internet
Author: User

// When there are many attributes and methods, writing is not very convenient. You can write them in json format.
// Because the prototype is not specified through Person. prototype, the constructor will not point to Person but to Object.
// If constructor is really important, you can describe the prototype in json.
Function Person (){

}

Person. prototype = {
// Constructor: Person, // manually specify a constructor
Name: "octopus ",
Age: 23,
Say: function (){
Alert (this. name + ":" + this. age );
}
}
Var p1 = new Person ();
P1.say (); // octopus: 23
Alert (p1.constructor = Person); // false

Person. prototype. sayHi (){
Alert (this. name + ": hi ");
}
P1.sayHi (); // octopus: hi

// If the prototype is rewritten to new Person (), p1.sayHi (); // undefined: hi
Function Person (){

}

Var p1 = new Person ();

Person. prototype. sayHi (){
Alert (this. name + ": hi ");
}
P1.sayHi (); // undefined: hi

Person. prototype = {
// Constructor: Person, // manually specify a constructor
Name: "octopus ",
Age: 23,
Say: function (){
Alert (this. name + ":" + this. age );
}
}
P1.sayHi (); // undefined: hi has sayHi (), but no name

Var p2 = new Person ();
P2.sayHi (); // error: sayHi is not a function. This is because p2 does not have sayHi

 

Original article reprinted, please indicate the source, this article first in the csdn Website: http://blog.csdn.net/magneto7/article/details/24922481

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.