How to understand JS prototype object

Source: Internet
Author: User

1. all objects have prototype objects.

2. prototype objects, which are static properties and static methods in classes in other languages, are always static-static. The principle is that there is only one copy in memory.

In-memory plots:

Write a constructor first:

function person (name, age) {this.name = name; This.age = age;} var A = new Person (' A ', +), var B = new Person (' B ', '); var C = new Person (' C ', 38);

function person (name, age) {this.name = name;    This.age = age; This.location = ' Earth ';} var A = new Person (' A ', +), var B = new Person (' B ', '); var C = new Person (' C ', 38);

All three objects have a memory space of "Earth". Here you have to move the brain, three people have the Earth's memory, we can not do this?

The most important function of a prototype object is to separate the constants and methods into itself. Supply other "own objects" to use. Last:

4. Implement it from the code.

function person (name, age) {this.name = name; This.age = age;} var A = new Person (' A ', +), var B = new Person (' B ', '); var C = new Person (' C ', 38); Person.prototype.location = ' Earth '; Person.prototype.killPerson = function () {console.log (' kill!!! ');} A.location//Earth A.killperson ()//Kill manb.location//Earth

However, the premise is that there is no location or Killperson defined in your object attributes. Otherwise, the original object will be overwritten.

In A.location, first, we examine the A object itself, and we know that A has the name, age, and prototype pointer properties. There is no location, can not find the future, it will continue to search the original object inside, see if you can find the Location property, if any, will call the original object's properties.


How to understand JS prototype object

Related Article

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.