search
HomeWeb Front-endJS TutorialUnderstanding Javascript_11_constructor implementation principle_javascript skills

What is constructor

To understand simply, constructor refers to the constructor of an object. Please see the following example:

Copy code The code is as follows:

function Foo(){};
var foo = new Foo();
alert(foo.constructor);//Foo
alert(Foo.constructor);//Function
alert(Object.constructor);//Function
alert(Function.constructor);//Function

For foo.constructor is Foo, I think it should be easy to understand, because the constructor of foo is Foo. I think there is nothing controversial about the fact that the constructor of Foo, Object, and Function is Function. (Because Foo, Object, and Function are all function objects, and because all function objects are constructed from the Function object, their constructor is Function. For details, please refer to "js_Function Object")

The relationship between Prototype and Constructor

Copy code The code is as follows:

function Dog() {}
alert(Dog === Dog.prototype.constructor);//true

In JavaScript, each function has an attribute named "prototype", which is used to reference the prototype object. This prototype object in turn has a property called "constructor" which in turn refers to the function itself. This is a circular reference, as shown in the figure:
Understanding Javascript_11_constructor implementation principle_javascript skills
Where does the constructor attribute come from?
Let’s take a look at the construction process of Function constructing String:
Understanding Javascript_11_constructor implementation principle_javascript skills
Note: Function constructor The process of any function object is the same, so whether it is a built-in object such as String, Boolean, Number, etc., or a user-defined object, the construction process is the same as the above figure. String here is just a representative!
As can be seen in the figure, constructor is generated by Function when it creates a function object. As mentioned in the 'Relationship between prototype and constructor', constructor is an attribute in the function object prototype chain. That is String=== String.prototype.constructor.

I also want to use a piece of code to prove that the theory is correct:
Copy the code The code is as follows:

function Person(){}
var p = new Person();
alert(p.constructor);//Person
alert(Person.prototype.constructor) ;//Person
alert(Person.prototype.hasOwnProperty('constructor'));//true
alert(Person.prototype.isPrototypeOf(p));//true
alert(Object.prototype .isPrototypeOf(p));//true
alert(Person.prototype == Object.prototype);//false

By now, you will find that this is the same as the previous "Prototype Chain" The default prototype in "Implementation Principles" points to Object.prototype, which conflicts. Obviously, the theory at that time was not very comprehensive.

Special Object
Careful readers may ask this question, your theory does not apply to Object. Because the following code conflicts with your theory above:
Copy code The code is as follows:

alert(Object.prototype.hasOwnProperty('constructor'));//true
alert(Object.prototype.hasOwnProperty('isPrototypeOf'));//true, according to the above theory, false should be returned here

Is this really the case? no! Then let’s take a look at how special Objects are processed:
Understanding Javascript_11_constructor implementation principle_javascript skills
You will find that the principle of this picture is the same as the principle of the above picture. This can correctly explain that Object.prototype.hasOwnProperty('isPrototypeOf') is true!

constructor exploration
Copy code The code is as follows:

function Animal(){}
function Person(){}
var person = new Person();
alert(person.constructor); //Person

Based on the content of the previous section, can you correctly understand the result of this code? After thinking about it, take a look at its memory representation:
Understanding Javascript_11_constructor implementation principle_javascript skills
This picture clearly shows the process of Function constructing Animal and Person. It also shows the relationship between the instance person and Person.

Go a little deeper, the code is as follows:
Copy the code The code is as follows:

function Animal(){}
function Person(){}
Person.prototype = new Animal()
var person = new Person()
alert(person) .constructor); //Animal

이때 person의 생성자는 어떻게 설명할까요?
Understanding Javascript_11_constructor implementation principle_javascript skills
참고: 그림의 점선은 Person의 기본 프로토타입 포인터를 나타냅니다(참고용). 하지만 우리는 Person.prototype을 새로운 Animal로 지정했습니다.
이때 Person의 프로토타입은 Animal의 인스턴스를 가리키므로 person의 생성자는 Animal의 생성자가 됩니다.

결론: 생성자의 원리는 매우 간단합니다. 즉, 객체의 프로토타입 체인에서 생성자 속성을 찾는 것입니다.

참고: 이 기사의 내용을 정확하게 이해할 수 없다면 이전 장의 내용을 검토하시기 바랍니다.
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools