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