Home  >  Article  >  Web Front-end  >  Introduction to the relationship between constructors and prototype chains in JavaScript

Introduction to the relationship between constructors and prototype chains in JavaScript

不言
不言forward
2019-02-23 17:04:282234browse

This article brings you an introduction to the relationship between constructors and prototype chains in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The concept of class does not exist in Javascript. Its class concept is realized through the constructor and prototype chain.

1. Constructor: The initialization object when creating an object always appears together with the new key.

The constructor has the following characteristics:
1. This in the constructor points to the current instance object.
2. Use the new keyword to instantiate the current object.
3. Capitalize the first letter of the constructor to distinguish ordinary functions.
4. All instance objects can inherit the properties and methods in the constructor. However, properties cannot be shared between instances of the same object.

2. Prototype: It is an object that implements attribute inheritance of the object. Objects in javascript point to the prototype object through proto, which can be accessed through Object.__proto__

3. Constructor and connection with the prototype:

   <script>
   function  Demo(){
            
     }
     var demo = new Demo()
     var  data= demo.prototype = function(){

     }
    
     console.log(demo.__proto__)
     console.log(data.constructor )
     console.log(data.prototype.__proto__)
     console.log(demo.constructor.prototype)
     console.log(demo.constructor)
    输出:
    {constructor: ƒ}constructor: ƒ Demo()__proto__: Object
    ƒ Function() { [native code] }
    {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
    {constructor: ƒ}
    ƒ Demo(){    }
</script>

Output from the above The results can be seen:

The __proto__ of the constructor points to the prototype object;
The constructor of the prototype points to the constructor Function;
The prototype's prototype.__proto__ is equal to Object.__proto__;
The constructor of the instance .prototype points to the prototype;
The constructor of the instance points to the constructor

Quote legend:
![1460000018155881][1]

The above is the detailed content of Introduction to the relationship between constructors and prototype chains in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete