Table of Contents
1) Look at three examples
1.1 No return statement
1.2 return object type data
1.3 Return basic type data
2) The principle behind
2.1 The case of non-arrow functions
What if the constructor is an arrow function?
3.1 Chinese description and related code analysis
Any function except arrow functions can be used
3.2 更简洁的语言描述
4)几点说明
4.1 判断是否是 Object 类型
4.2 instanceof 原理
Home Web Front-end JS Tutorial Introduction to the principle of new calling function in JS

Introduction to the principle of new calling function in JS

Jul 10, 2018 pm 05:38 PM
javascript front end

This article mainly introduces the principle of new calling function in JS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Constructor is often used in JavaScript to create Object (calling a function through the new operator), what exactly happens when calling a function using new? Let’s look at a few examples before explaining what’s going on behind the scenes.

1) Look at three examples

1.1 No return statement

There is no return statement at the end of the constructor. This is also the default situation when using the constructor. Finally, a new object will be returned, as follows:

function Foo(age) {
  this.age = age;
}

var o = new Foo(111);
console.log(o);
Copy after login

This is a common process of using a constructor to create an object, and what is printed is {age: 111}.

1.2 return object type data

Constructor lastreturnObject type data:

function Foo(age) {
  this.age = age;

  return { type: "我是显式返回的" };
}

var o = new Foo(222);
console.log(o);
Copy after login

What is printed is{type: 'I It is explicitly returned'}, that is to say, all the work before return is done in vain, and finally the object after return is returned.

1.3 Return basic type data

Does that mean that as long as there is return at the end of the constructor body, the data after return will be returned?

Let’s take a look at the situation of returning basic type data:

function Foo(age) {
  this.age = age;

  return 1;
}

var o = new Foo(333);
console.log(o);
Copy after login

What is printed is {age: 333}, and the effect when there is no return Same. It’s different from expectations. Please see the analysis below for the principle behind it.

2) The principle behind

2.1 The case of non-arrow functions

When using the new operator to create an object, the ES5 official documentation is in Function definition The following definition is made in section 13.2.2 [[Construct]]:

When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:

  1. Let obj be a newly created native ECMAScript object.

  2. ##Set all the internal methods of obj as specified in 8.12.

  3. Set the [[Class] ] internal property of obj to Object.

  4. Set the [[Extensible]] internal property of obj to true.

  5. Let proto be the value of calling the [[Get]] internal property of

    F with argument "prototype".

  6. ##If Type(proto) is Object, set the
  7. [[Prototype]] internal property of obj to proto

    .

  8. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in
  9. Object prototype object

    as described in 15.2.4.

  10. Let result be the result of calling the [[Call]] internal property of F,
  11. providing obj as the this value

    and providing the argument list passed into [[Construct]] as args.

  12. If Type(result) is Object then return result

    .

  13. Return obj.
  14. See steps 8 and 9:

8) Call function

F
, assign its return value to result; among them, the actual parameters when F is executed are passed to [[Construct]] (that is, F itself) parameter, F internal this points to obj; 9) If result
is Object type, returns result;
This also explains that if the constructor explicitly returns the object type, it will return the object directly instead of returning the originally created Object.

Finally look at step 10:

10) If

F
returns not an object type (step 9 is not true), return the created object obj.
If the constructor does not explicitly return the object type (explicitly returns the basic data type or does not return it directly), the initially created object is returned.

2.2 The case of arrow function

What if the constructor is an arrow function?

There is no

[[Construct]]

method in the arrow function, and it cannot be called using new, and an error will be reported. NOTICE:

[[Construct]]

refers to the constructor itself. Relevant specifications are mentioned in the official documentation of ES6, but the official documentation since ES6 is extremely difficult to understand and will not be described here.

3) The complete process of new calling function

Any function except arrow functions can be used

new

What happens behind the call is very clear in English in the previous section, and it is described in Chinese as follows: <p>1)创建 ECMAScript 原生对象 <code>obj;  
2)给 obj 设置原生对象的内部属性;(和原型属性不同,内部属性表示为 [[PropertyName]],两个方括号包裹属性名,并且属性名大写,比如常见 [[Prototype]][[Constructor]])  
3)设置 obj 的内部属性 [[Class]]Object;  
4)设置 obj 的内部属性 [[Extensible]]true;  
5)将 proto 的值设置为 Fprototype 属性值;  
6)如果 proto 是对象类型,则设置 obj 的内部属性 [[Prototype]] 值为 proto;(进行原型链关联,实现继承的关键)  
7)如果 proto 是不对象类型,则设置 obj 的内部属性 [[Prototype]] 值为内建构造函数 Objectprototype 值;(函数 prototype 属性可以被改写,如果改成非对象类型,obj[[Prototype]] 就指向 Object 的原型对象)  
8)9)10)见上节分析。(决定返回什么)

对于第 7 步的情况,见下面代码:

function Foo(name) {
  this.name = name;
}

var o1 = new Foo("xiaoming");
console.log(o1.__proto__ === Foo.prototype); // true

// 重写构造函数原型属性为非对象类型,实例内部 [[Prototype]] 属性指向 Object 原型对象
// 因为实例是一个对象类型的数据,默认会继承内建对象的原型,
// 如果构造函数的原型不满足形成原型链的要求,那就跳过直接和内建对象原型关联
Foo.prototype = 1;
var o2 = new Foo("xiaohong");
console.log(o2.__proto__ === Foo.prototype); // false
console.log(o2.__proto__ === Object.prototype); // true
Copy after login

3.2 更简洁的语言描述

若执行 new Foo(),过程如下:

1)创建新对象 o;  
2)给新对象的内部属性赋值,关键是给[[Prototype]]属性赋值,构造原型链(如果构造函数的原型是 Object 类型,则指向构造函数的原型;不然指向 Object 对象的原型);  
3)执行函数 Foo,执行过程中内部 this 指向新创建的对象 o;  
4)如果 Foo 内部显式返回对象类型数据,则,返回该数据,执行结束;不然返回新创建的对象 o

4)几点说明

4.1 判断是否是 Object 类型

关于一个数据是否是 Object 类型,可以通过 instanceof 操作符进行判断:如果 x instanceof Object 返回 true,则 xObject 类型。

由上可知,null instanceof Object 返回 false,所以 null 不是 Object 类型,尽管typeof null 返回 "Object"。

4.2 instanceof 原理

instanceof 的工作原理是:在表达式 x instanceof Foo 中,如果 Foo 的原型(即 Foo.prototype)出现在 x 的原型链中,则返回 true,不然,返回 false

因为函数的原型可以被改写,所以会出现在 x 通过 Foo new 出来之后完全改写 Foo 的原型 x instanceof Foo 返回 false 的情况。因为实例创建之后重写构造函数原型,实例指向的原型已经不是构造函数的新的原型了,见下面代码:

const Foo = function() {};

const o = new Foo();

o instanceof Foo; // true

// 重写 Foo 原型
Foo.prototype = {};
o instanceof Foo; // false
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

The above is the detailed content of Introduction to the principle of new calling function in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles