In-depth exploration of JS prototype and prototype chain

Source: Internet
Author: User

Recently in the read "JavaScript Advanced Programming", after reading, feel the feeling, and then I saw an article today, said very funny. Just want to tidy up what you have learned.

First, if we think of the ECMAScript object as a hash table , a set of name-value pairs , where the value can be data or function.

What about objects, prototype objects, constructors, inheritance, prototype chains, the sharing of prototype attributes, the dynamics of prototypes, the overall rewriting of prototypes, a simple set of rough descriptions, huh, or quite funny.

1) Man is a man who is born of a mother, a demon is born of a demon. Both the man and the demon are the object instances, and the man's mother and Demon are the prototypes. Prototypes are also objects, called prototype objects.

2) People his mother and the people his father snapped can give birth to a bunch of baby, demon his mother and demon his father can give birth to a bunch of demon Baby, PA PA is the structure function, commonly known as building people.

3) The person will be able to record the information, so you can get the information through the person's mother, that is, the prototype object can find the constructor function.

4) People can give birth to a lot of babies, but these babies have only one mother, which is the uniqueness of the prototype.

5) The person who is the mother is also the mother of the mother born, through the people his mother to find the mother of the hell, and then through the human mother to find the mother damn ..., this relationship is called the prototype chain.

6) The prototype chain is not infinite, when you go through the human mother to look up, and finally found that you will find the mother of the damn ... The mother is not a human, that is, the prototype chain eventually points to null.

7) The person who the mother born person will be someone's appearance, demon his mother born Demon will have demon ugly, this is called Inherit.

8) You have inherited your mother's skin color, your mother has inherited your mother's fucking complexion, your mother fucking ..., this is the inheritance of the prototype chain.

9) You talk about the object, her mother let you take the property card to pick up, if you do not, then her mother will ask your mother whether, your mother did not that her mother will ask your mother her mother has not ... This is the upward search of the prototype chain.

10) You will inherit your mother's appearance, but you can also dye the hair to wash and cut, that is, the properties of the object can be customized, overwriting inherited properties.

11) Although you have washed and dyed yellow hair, but you can not change your mother's appearance, your mother's brother and sister with your yellow hair wash cut no matter, that the object instance cannot change the properties of the prototype.

12) But your family was burned by you, that is to say your home your mother's family are burned, this is the prototype attribute sharing.

13) Your mother's nickname Jane, the neighbor Niang all call you Jane son, but your mother hair from fluttering soft made of Golden Lion Queen, next door aunt all changed to call you chartered, this is called the dynamic nature of the prototype.

14) Your Mother beauty, and ran to South Korea plastic surgery, the whole to your mother can not recognize the mother, even if your mother's hair change back, but next door neighbor still call you Golden Lion Prince. Because no one recognized your mother, the plastic after your mother has melted down re-established, this is the overall rewrite of the prototype.

Haha, is not simple rough, but also particularly easy to understand.

There are two types of properties in ECMAScript: Data properties and accessor properties
(1) Data properties:

[[Configurable]] indicates whether the property can be redefined by deleting the property, whether the property can be modified, or whether the property can be modified as an accessor property
[[[Enumerable]] indicates the ability to return a property through a for-in loop
[[writable]] indicates whether the value of the property can be modified
[[Value]] contains the data value of this property,
Modify the default property using the Object.defineproperty () method

(2) Accessor properties: Contains getter and setter functions. Getter: Responsible for returning a valid value, the Setter function passed in the new value, accessor properties of the 4 attributes:
[[[Configurable]] indicates whether the property can be redefined by deleting the property through the Delete property, can the attribute be modified, or the property can be modified to a data property. The default is true.
[[Enumerable]] Indicates whether the property can be returned through a for-in loop.
The function that is called when the property is read [[Get] , the default value is undefined
The function that is called when the property is written [[Set] , the default value is undefined

Accessor properties are defined with object.defineproperty ()

The book gives an example to be quite well understood:

var book = {
_year:2004,
_year the preceding underscore is a common notation, * * to represent properties accessible only through object methods * *
Edition:1
};
Object.defineproperty (book, ' Year ', {
Get:function () {
return this._year;
}
Set:function (newyear) {
if (NewValue >2004) {
This._year = newvalue;
This.edition + = newValue-2004;
}
}
});
To define an old method of an accessor
BOOK.__DEFINEGETTER__ ("Year", function () {
return this._year;
})
BOOK.__DEFINESETTER__ ("Year", function (NewValue) {
if (NewValue >2014) {
This._year = newvalue;
This.edition + = newValue-2004;
}
})

Book.year = 2015;
alert (book.edition); 2
Attributes of the Read attribute:object.getownpropertydesciptor () Gets the descriptor for the given property.

Finally, back to the prototype chain: The main problem of the prototype chain inheritance is the sharing of attributes, many times we just want to share the method and do not want to share the property, ideally each instance should have a separate attribute. As a result, there are two ways to improve the prototype inheritance:

1) Combination Inheritance

function Mother (age) {

This.age = age;

This.bobby = [' Running ', ' football ']

}

Mother.prototype.showAge = function () {

Console.log (This.age);

};

function Person (name,age) {

Mother.call (This.age); Second execution

THIS.name = name;

}

Person.prototype = new mother (); First time execution

Person.prototype.constructor = person;

Person.prototype.showName = function () {

Console.log (this.name);

}

var p1 = new Person (' Jack ', 20);

P1.hobby.push (' basketball '); P1: ' Jack '; _proto_:20,[' running ', ' football ']

var p2 = new Person (' Mark ', 18); P2: ' Mark '; _proto_:18,[' running ', ' football ']

(2) Parasitic combined inheritance

function Object (o) {

function F () {}

F.prototype = O;

return new F ();

}

function Inheritprototype (person,mother) {

var prototype = object (Mother.prototype);

Prototype.constructor = person;

Person.prototype = prototype;

}

function Mother (age) {

This.age = age;

This.hobby = [' Running ', ' football ']

}

Mother.prototype.showAge = function () {

Console.log (This.age);

};

function Person (name,age) {

Mother.call (This,age);

THIS.name = name;

}

Inheritprototype (Person,mother);

Person.prototype.showName = function () {

Console.log (this.name);

}

var p1 = new Person (' Jack ', 20);

P1.hobby.push (' Backetball '); P1: ' Jack '; _proto_:20,[' running ', ' football ']

var p2 = new Person (' Mark ', 18); P2: ' Mark '; _proto_:18,[' running ', ' football ']

JS create objects in various ways

(1) Prototype mode

1 prototype mode: Object Literal method

var person = {

Name: ' Jack ',

Age:18,

Sayname:function () {alert (this.name);}

};

2 prototype Mode: Object Constructor method

var person = new Object ();

Person.name = ' Jack ';

Person.age = 18;

Person.sayname = function () {

alert (this.name);

};

(2) Factory mode

Factory mode, define a function to create an object

function Creatperson (name,age) {

var person = new Object ();

Person.name = name;

Person.age = age;

Person.sayname = function () {

alert (this.name);

};

return person;

}

Factory mode is mass production, simple call can enter the creation of human mode (PA pa ... Specify the name age can build a bunch of small babies, free hands. But because it is factory-rigged, so you can not identify the object exactly what type, is a person or a dog silly (instanceof test as Object), in addition to each time the creation of a separate temp object, the code is bloated

(3) Constructors

3 constructor mode, defining a constructor for an object

function Person (name,age) {

THIS.name = name;

This.age = age;

This.sayname = function () {

alert (this.name);

};

}

var p1 = new Person (' Jack ', 18); Create a P1 object

Person (' Jack ', 18);

Constructors are similar to the constructors of classes in C + +, Java, and are easy to understand, and the person can be identified as type (instanceof test for person, Object). But all instances are still independent, and the methods of the different instances are actually different functions. Here to forget the function two words, the sayname as an object to understand, that is to say Zhang San Sayname and John Doe Sayname is different existence, but obviously we expect to share a sayname to save memory.

(4) Prototype mode

Prototype mode, directly defining the prototype property

function person () {}

Person.prototype.name = ' Jack ';

Person.prototype.age = 18;

Person.prototype.sayName = function () {alert (this.name);};

Prototype mode. How to define the literal quantity

function person () {}

Person.prototype = {

Name: ' Jack ',

Age:18,

Sayname:function () {alert (this.name);}

};

var p1 = new Person (); name = ' Jack '

var p2 = new Person (); name = ' Jack '

It is important to note that there is a sharing of prototype properties and methods, that is, all instances only refer to the attribute methods in the prototype, and any changes that occur in any one place can cause changes to other instances.

(5) Mixed mode

Prototype constructor combination mode

function Person (name,age) {

THIS.name = name;

This.age = age;

}

Person.prototype = {

hobby:[' running ', ' Football '];

Sayname:function () {alert (this.name);},

Sayage:function () {alert (this.age);}

}

var p1 = new Person (' Jack ', 20);

var p2 = new Person (' Mark ', 18);

The practice is to put a separate attribute method into the constructor, while the part that can be shared is put into the prototype, which minimizes memory and preserves the independence of the object instance.

In-depth exploration of JS prototype and prototype chain

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.