Introduction to the principle of new calling function in JS
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);
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 lastreturn
Object type data:
function Foo(age) { this.age = age; return { type: "我是显式返回的" }; } var o = new Foo(222); console.log(o);
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);
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:
Let obj be a newly created native ECMAScript object.
- ##Set all the internal methods of obj as specified in 8.12.
- Set the [[Class] ] internal property of obj to Object.
- Set the [[Extensible]] internal property of obj to true.
- Let proto be the value of calling the [[Get]] internal property of
F with argument "prototype".
##If Type(proto) is Object, set the - [[Prototype]] internal property of obj to proto
.
If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in - Object prototype object
as described in 15.2.4.
Let result be the result of calling the [[Call]] internal property of F, - providing obj as the this value
and providing the argument list passed into [[Construct]] as args.
- If Type(result) is Object then return result
.
Return obj. - See steps 8 and 9:
8) Call function
F, assign its return value toThis also explains that if the constructor explicitly returns the object type, it will return the object directly instead of returning the originally created Object.result
; among them, the actual parameters whenF
is executed are passed to[[Construct]]
(that is,F
itself) parameter,F
internalthis
points toobj
;9) If
result
isObject
type, returnsresult
;
Finally look at step 10:
10) If
Freturns not an object type (step 9 is not true), return the created objectIf 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.obj
.
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:
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
3.1 Chinese description and related code analysis
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
的值设置为 F
的 prototype
属性值;
6)如果 proto
是对象类型,则设置 obj
的内部属性 [[Prototype]]
值为 proto
;(进行原型链关联,实现继承的关键)
7)如果 proto
是不对象类型,则设置 obj
的内部属性 [[Prototype]]
值为内建构造函数 Object 的 prototype
值;(函数 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
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
,则 x
为 Object
类型。
由上可知,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
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
