JavaScript prototype prototype

Source: Internet
Author: User
Tags hasownproperty

As mentioned in the article on JavaScript creation objects: One problem with creating objects with constructors is that the same method for different instances of the same constructor is not the same, so we use prototypes to extract the public properties and methods of the constructor for encapsulation. Achieve the purpose of having all instances shared.

Next you'll learn more about JavaScript prototypes.

First, JavaScript prototype mechanism 1, the relationship between function and prototype

JS creates a function, it automatically creates a prototype property that points to the prototype object of the function, and the prototype object automatically obtains a constructor (constructor) attribute, pointing to the function.

Example: Create an object in the previous prototype schema as an example

View Code

The relationship between the person object and the prototype of the person object, such as 1.

Figure 1 The relationship between the function, the instance and the prototype (Figure JS elevation)

The simple word is: Person.prototype.constructor point to Person, you can test in the browser.

2. The relationship between examples and prototypes

Creates an instance from a constructor that contains a property (pointer) that points to the constructor's prototype object.

Example: the instance of the person constructor Person1 and Person2 's [[Prototype]] property point to the person's prototype. As shown in 1.

Note:[[Prototype]] The connection is between the prototype of the instance and the constructor , not between the instance and the constructor.

For this pointer, ECMA-262 [[Prototype]], there is no standard way to access [[Prototype]], but Firefox, Safari, and chrome support one property __protp__ on each object, and in other implementations, This property is not visible to scripts.

3. Prototype chain

The instance has its own properties and methods, and the prototype encapsulates the properties and methods shared by all instances, and how is this kind of sharing implemented? The answer is the prototype chain.

When you want to access the properties of an instance, the parser performs a search. Starting with the instance object, the value of the property is returned if it is found in the instance, and the focus is to continue searching for the prototype object that the [[Prototype]] pointer points to, find the property in the prototype object, and return the value of the property if found. So multiple instances in this way can share the properties and methods stored in the prototype. This is also the JS prototype chain.

Note: Understanding the prototype chain, it is natural to understand a few problems.

A, adding a property to the instance with the same name as the prototype, it will be masked. Because searching the prototype chain can be found in the instance and then returned, it is impossible to prototype.

b, the value in the prototype can be accessed through the instance crawl prototype chain, but the value in the prototype cannot be overridden by an instance. Similarly.

C, the dynamic nature of the prototype, new properties or methods in the prototype can be immediately reflected from the instance.

Ii. prototype-related methods Introduction 1, isPrototypeOf () method

Although the [[Prototype]] property of the instance cannot be accessed, we can confirm the relationship between the prototype and the instance through the isPrototypeOf () method. This method is to stand at the prototype point of view to detect the prototype is not an instance of the prototype. A.isprototypeof (b) returns false if the prototype of B of a is returned true.

For example: Because two instances of person lxy and persona have a [[Prototype]] property that points to Person.prototype. So the isPrototypeOf method returns True.

<script type= "Text/javascript" >    function Person () {    }    person.prototype.name= "Lxy";    person.prototype.age=22;    person.prototype.job= "Software Engineer";    Person.prototype.sayname=function () {        alert (this.name);    }    var lxy=new person ();    var persona=new person ();    Console.log (Person.prototype.isPrototypeOf (LXY)); True    Console.log (Person.prototype.isPrototypeOf (PersonA));//true</script>
2. Object.getprototypeof () method

This method is new in ECMAScript 5 and returns the [[Prototype]] value of the instance.

This method is very useful because it is implemented on an object. So throw any instance to object, it can get the prototype of the instance.

Example

<script type= "Text/javascript" >    function Person () {    }    person.prototype.name= "Lxy";    person.prototype.age=22;    person.prototype.job= "Software Engineer";    Person.prototype.sayname=function () {        alert (this.name);    }    var lxy=new person ();    Console.log (object.getprototypeof (Lxy));    Console.log (object.getprototypeof (LXY) ==person.prototype); True    Console.log (object.getprototypeof (LXY). Age);//22</script>

Results:

3. Hasownprototype () method

This method is used to detect whether a property actually exists in the instance. is return ture, otherwise false is returned.

Just like we have some resources and skills, but we can also get some resources and skills from parents, such as looks like you have a villa, but you need to know what you really belong to yourself, which are parents to you.

Example: When I was born my parents gave me a name lxy, this time I use the Hasownprototype () method to detect this "name" property is not really mine, will return false.

Then I changed my name starof, and then I tested it with the Hasownprototype () method, and it returns true.

Then I didn't want to use the name, so I deleted it and used my parents ' name back. This time again using the Hasownprototype () method to detect whether the "name" property is my own, will return false.

This twists story code is as follows:

<script type= "Text/javascript" >    function Person () {    }    person.prototype.name= "Lxy";    var lxy=new person ();    Console.log (lxy.name);    Console.log (Lxy.hasownproperty ("name"));  False     lxy.name= "starof";//Override the Stereotype property name by overriding it, so this name becomes an instance attribute    Console.log (lxy.name);    Console.log (Lxy.hasownproperty ("name"));  True    Delete lxy.name;    Console.log (lxy.name);    Console.log (Lxy.hasownproperty ("name"));  False</script>
4, in operator, for-in Loop, object's keys () and Getownpropertynames ()

The In operator returns True when the property is accessible through an object , whether the property is an instance property or a prototype property.

The for-in loop returns all the enumerable properties that can be accessed through the object . That is, instance properties are also included in the prototype properties.

Instance properties that mask non-enumerable properties in the prototype are also returned in the for-in loop because, as a rule, all developer-defined properties are enumerable-except in IE8 and earlier versions.

The Object.keys () method, which gets all the enumerable instance properties on the instance . The method receives an instance as a parameter and returns an array of strings containing all the enumerable properties.

The Object.getownpropertynames () method obtains all instance properties , regardless of whether it is enumerable.

View code Three, the first type of prototype syntax: Each add a property and method, are directly on the prototype Add.
<script type= "Text/javascript" >    function Person () {    }    person.prototype.name= "Lxy";    person.prototype.age=22;    person.prototype.job= "Software Engineer";    Person.prototype.sayname=function () {        alert (this.name);    }    var lxy=new person ();</script>
The second type: The method of the object literal
<script>    Function Person () {    }    person.prototype={        name: "Lxy",        age:22,        job: " Software Engineer ",        sayname:function () {            alert (this.name);        }    };    var lxy=new person ();</script>

The second syntax is relatively simple, write fewer lines of code, but one thing to note is that the literal form completely overrides the prototype attribute, so constructor no longer points to person, but to object.

View Code

If constructor is important, you can manually set it to person, as follows.

<script>    Function Person () {    }    person.prototype={        Constructor:person,        name: "Lxy",        age:22,        job: "Software Engineer",        sayname:function () {            alert (this.name);        }    };    var lxy=new person ();    Console.log (Lxy.constructor==person);//true    Console.log (lxy.constructor==object);//false</script>

However, this will result in the constructor [[Enumerable]] attribute being set to true. Because developer-defined properties are all enumerable.

If the JS engine is compatible with ECMASCRIPT5, the object.defineprototype can be used.

View Code

The author starof, because the knowledge itself in the change, the author is also constantly learning and growth, the content of the article is not updated regularly, in order to avoid misleading readers, convenient tracing, please reprint annotated source: http://www.cnblogs.com/starof/p/4904929. HTML has a problem welcome to discuss with me, common progress.

JavaScript prototype prototype

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.