JavaScript Object-oriented series 5--knowledge points (prototypes and prototype chains)

Source: Internet
Author: User
Tags hasownproperty

Basic concepts

Prototype chain each constructor has an object, and the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. Then, if the prototype object equals an instance of another prototype, the prototype object will contain a pointer to another prototype, and a pointer to another constructor is also included in the other prototype. If another prototype is an instance of another prototype, the above relationship is still true. The progression of such layers constitutes the chain of examples and prototypes.


The "Prototype object" object contains properties and methods that can be shared by all instances of a particular type. All reference types inherit object by default, and this inheritance is implemented through the prototype chain. The default prototype for all functions is an instance of object, so the default prototype will contain an internal pointer to Object.prototype, which is why all custom types inherit the ToString (), ValueOf () method


The constructor constructor differs from other functions in the way they are called. In general, a function can be used as a constructor only if it is called by the new operator, and it will not be the same as a normal function if it is not called by the new operator.
[note] user-defined functions and constructors built into JavaScript can be used as constructors
The constructor constructor should always start with a capital letter, not a constructor that starts with a lowercase letter. This approach is borrowed from other OO languages, mainly to distinguish it from other functions in ECMAScript, because the constructor itself is a function, but it can be used to create objects.
"Three usage scenarios for constructors"
[A] use as a constructor

var New Person ("Nicholas","software Engineer"); Person.sayname ();

[B] as a normal function call

Person ("Greg","doctor"); // Add to Windowwindow.sayname (); // "Greg"

[C] is called in the scope of another object

var New Object (); Person.call (o,"Kristen","nurse"); o . Sayname (); // "Kristen"

The prototype property creates a prototype property for the function based on a specific set of rules, as long as a new function is created, which points to the prototype object of the function.
[note] Only functions have prototype properties, object has no prototype property


Constructor property By default, all prototype objects automatically get a constructor (constructor) property that contains a pointer to the function where the prototype property is located
[note] After the custom constructor has been created, its prototype object will only get the constructor property by default, and the other methods are inherited from Object


"_proto_ and [[prototype]]" when the constructor is called to create a new instance, the inner part of the instance contains a pointer (internal property) that points to the constructor's prototype object. ECMA-262 5th Edition Tube This pointer is called [[prototype]]. Although [[prototype] is accessed in a standard way in scripting, Firefox\safari\chrome supports one property _proto_ on each object, and in other implementations, this property is completely invisible to the script. This connection exists between the instance and the constructor's prototype object, not between the instance and the constructor

Basic operations

The prototype chain query executes a search whenever the code reads a property of an object, and the target is a property with the given name. The search starts first from the object instance itself, returns the value of the property if it finds a property with the given name in the instance, and if it is not found, continues the search for the prototype object pointed to by the pointer, finds the property with the given name in the prototype object, and returns the value of the property if it is found.


Add Instance property when you add a property to an object instance, this property masks the property of the same name saved in the prototype object; in other words, adding this property will only prevent us from accessing that property in the prototype, but it will not modify that property, even if the property is set to NULL, it will only be set in the instance. The connection to the prototype is not restored. However, using the delete operator allows you to completely remove the instance properties, allowing us to revisit the properties in the prototype.


"The dynamics of prototypes" because the process of looking up values in a prototype is a search, any modifications we make to the prototype object are immediately reflected from the instance, even if the prototype was modified before the instance was created.
[note] It is not recommended to modify native object prototypes in a production program

function Person () {}; var New  function() {    alert (' Hi ');} Friend.sayhi (); // "HI"    

When the constructor is called by the Override prototype, a [[prototype]] pointer to the original prototype is added to the instance, and modifying the prototype to another object is tantamount to cutting off the connection between the constructor and the original prototype. The pointer in the instance only points to the prototype, not to the constructor.

Basic methods

[1]isprototypeof (): To determine whether the instance object and the prototype object exist in the same prototype chain, as long as the prototype chain has appeared in the prototype, it can be said that the prototype chain derived from the prototype of the instance

function Person () {}; var New Person (); var New Object (); Console.log (Person.prototype.isPrototypeOf (Person1)); // trueconsole.log (Object.prototype.isPrototypeOf (Person1)); // trueconsole.log (Person.prototype.isPrototypeOf (Person2)); // falseConsole.log (Object.prototype.isPrototypeOf (Person2)); // true

[2]ecmascript5 new Method Object.getprototypeof (): This method returns the value of [[Prototype]]

function Person () {}; var New Person (); var New  //person{}//true//false//  object{}    

[3]hasownproperty (): Detects if a property exists in the instance

function Person () {Person.prototype.name='Nicholas';}varPerson1 =NewPerson ();//does not exist in the instance, but exists in the prototypeConsole.log (Person1.hasownproperty ("name"));//false//does not exist in the instance, nor does it exist in the prototypeConsole.log (Person1.hasownproperty ("No"));//falsePerson1.name ='Greg'; Console.log (person1.name);//' Greg 'Console.log (Person1.hasownproperty ('name'));//trueDelete Person1.name;console.log (person1.name);//"Nicholas"Console.log (Person1.hasownproperty ('name'));//false

[4] ECMAScript5 object.getownpropertydescriptor (): Can only be used to get the descriptor of the instance property, to get the descriptor of the prototype property, The Object.getownpropertydescription () method must be called directly on the prototype object

function Person () {Person.prototype.name='Nicholas';}varPerson1 =NewPerson ();p erson1.name='Cook'; Console.log (Object.getownpropertydescriptor (Person1,"name"));//Object {value: "Cook", Writable:true, Enumerable:true, configurable:true}Console.log (Object.getownpropertydescriptor (Person.prototype,"name"));//Object {value: "Nicholas", Writable:true, Enumerable:true, configurable:true}

[5]in operator: Returns True when a given property is accessible through an object, whether the attribute exists in an instance or in a prototype

function Person () {}varPerson1 =NewPerson ();p erson1.name='Cook'; Console.log ("name" inchPerson1);//trueConsole.log ("name" inchPerson.prototype);//falsevarPerson2 =NewPerson (); Person.prototype.name='Cook'; Console.log ("name" inchPerson2);//trueConsole.log ("name" inchPerson.prototype);//true

[6] Use both the hasOwnProperty () method and the in operator to determine whether a property exists in the instance

//hasOwnProperty () returns false, and the in operator returns TRUE, the function returns True to determine that the property in the prototypefunctionHasprototypeproperty (object,name) {return!object.hasownproperty (name) && (nameinchobject);}functionPerson () {Person.prototype.name= ' Nicholas ';}varPerson1 =NewPerson (); Console.log (Hasprototypeproperty (Person1,' name '));//truePerson1.name = ' Cook '; Console.log (Hasprototypeproperty (Person1,' name '));//falseDeletePerson1.name;console.log (Hasprototypeproperty (Person1,' name '));//trueDeletePerson.prototype.name;console.log (Hasprototypeproperty (Person1,' name '));//false

[7] ECMAScript5 's Object.keys () method: Receives an object as a parameter, returns an array of strings containing all enumerable properties
[note] Be sure to first new out of the instance object before using this method, otherwise null

functionPerson () {Person.prototype.name= ' Nicholas '; Person.prototype.age= 29; Person.prototype.job= ' Software Engineer '; Person.prototype.sayName=function() {alert ( This. Name); }    };varKeys =Object.keys (Person.prototype); Console.log (keys);//[]varP1 =NewPerson ();p 1.name= "Rob";p 1.age= 31;varKeys =Object.keys (Person.prototype); Console.log (keys);//["Name", "Age", "job", "Sayname"]varP1keys =Object.keys (p1); Console.log (P1keys);//["Name", "Age"]

[8] ECMAScript5 's Object.getownpropertynames () method: Receives an object as a parameter, returns an array of strings containing all the properties
[note] Be sure to first new out the instance object and then use this method, otherwise only constructor

functionPerson () {Person.prototype.name= ' Nicholas '; Person.prototype.age= 29; Person.prototype.job= ' Software Engineer '; Person.prototype.sayName=function() {alert ( This. Name); }    };varKeys =object.getownpropertynames (Person.prototype); Console.log (keys);//["Constructor"]varP1 =NewPerson ();varKeys =object.getownpropertynames (Person.prototype); Console.log (keys);//["Constructor", "name", "Age", "job", "Sayname"]

Directory Links

"1" JavaScript Object-oriented series of understanding objects

"2" JavaScript Object-oriented series 2--9 ways to create objects

6 ways to implement inheritance for the "3" JavaScript Object-oriented series 3--

"4" JavaScript Object-oriented series 4--instance (simplest object-oriented tab)

"5" JavaScript Object-oriented series 5--knowledge points (this of 9 scenarios)

"6" JavaScript Object-oriented series 5--knowledge points (prototypes and prototype chains)

JavaScript Object-oriented series 5--knowledge points (prototypes and prototype chains)

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.