Preface
In the process of learning JavaScript, it is inevitable to encounter the new
operator. This time Let’s take a closer look and deepen our understanding and memory.
What is new operator?
The new
operator is defined in mdn like this:
new operator creates an instance of a user-defined object type or a built-in object with a constructor instance.
In this sentence, let’s look at a keyword: has a constructor
. What does this mean? Let’s take a look at a few examples first:
//例1let Animal1=function(){this.name=1};let animal=new Animal1; //这里不带()相当于不传参数//=>Animal1 {name: 1}//例2let TestObj={}let t1=new TestObj;//=>Uncaught TypeError: TestObj is not a constructor复制代码
We can see that Example 1 successfully executed the new
statement and created an instance. Example 2 reports an error TypeError: TestObj is not a constructor
in new
a {}
object, indicating that the target is not a constructor
. Why can't ordinary objects execute the new
operator? There is a relevant introduction in the ECMA specification:
If Type(argument) is not Object, return false.
If argument has a[[Construct]]
internal method , return true. Return false.
means:
- The constructor must first be an object, otherwise the condition is not met
-
Secondly, the object must have
[[Construct]]
internal method before it can be used as a constructor
Our {}
here is one Object satisfies the first condition, then obviously, it must be because {}
does not have the internal method [[Construct]]
, so the new
operator cannot be used Constructed.
So we have figured out the operable objects of the new
operator, can we take a look at its function? The answer is: NO! Let’s look at another example:
//例3let testObj={ Fn(){ console.log("构造成功!") } }let t3=new testObj.Fn;//=>Uncaught TypeError: testObj.Fn is not a constructor复制代码
what? Why can’t the function that was successfully constructed just now not work as a method? In fact, it is also directly introduced in MDN:
Methods cannot be constructors! They will throw a TypeError if you try to instantiate them.
means, methods Cannot be a constructor , if you try to create an instance of a method, a type error will be thrown. It makes sense to say this, but it’s not over yet. This statement does not fully explain the principle. Let’s look at another example:
//例4const example = { Fn: function() { console.log(this); }, Arrow: () => { console.log(this); }, Shorthand() { console.log(this); } };new example.Fn(); // Fn {}new example.Arrow(); // Uncaught TypeError: example.Arrow is not a constructornew example.Shorthand(); // Uncaught TypeError: example.Shorthand is not a constructor复制代码
Contrast this example, we checked in the ECMA specification and found that all functions depend on In FunctionCreate
Function:
FunctionCreate (kind, ParameterList, Body, Scope, Strict, prototype)
- If the prototype argument was not passed, then let prototype be the intrinsic object %FunctionPrototype%.
- If "kind" is not Normal, let allocKind be "non-constructor".
The definition of this function It can be seen that
- is a constructible function only when a function of type
Normal
is created, otherwise it is not constructible.
In our example, the type of Arrow
is Arrow
, and the type of ShortHand
is Method
, therefore are not constructible functions, which also explains what Example 3 says "Methods cannot be used as constructors".
After figuring out the targets that the new
operator can operate on, I can finally take a look at its function with a clear mind (not easy TAT).
What does the new operator implement?
Let’s take a simple example to see its function in detail:
function Animal(name){ this.name=name; console.log("create animal"); }let animal=new Animal("大黄"); //create animalconsole.log(animal.name); //大黄Animal.prototype.say=function(){ console.log("myName is:"+this.name); } animal.say(); //myName is:大黄复制代码
Let’s analyze it from this example. First, let’s look at this sentence:
let animal=new Animal("大黄");复制代码
You can see So, after executing the new
operator, we get a animal
object, then we know that the new
operator must create an object and convert this The object is returned. Look at this code again:
function Animal(name){ this.name=name; console.log("create animal"); }复制代码
At the same time, we see the result, create animal
is indeed output, we know that the Animal
function body is executed during this process , and the parameters were passed in at the same time, so our output statement was executed. But where is the sentence this.name=name
in our function body? This is the sentence:
console.log(animal.name); //大黄复制代码
After executing the function body, we find that the name
value of the returned object is the value we assigned to this
, so it is not difficult to judge. During this process, the value of this
points to the newly created object. There is another paragraph at the end:
Animal.prototype.say=function(){ console.log("myName is:"+this.name); } animal.say(); //myName is:大黄复制代码
animal
The object calls the method on the Animal
function prototype, indicating that Animal
is in animal
On the prototype chain of the object, which layer is it at? Let’s verify:
animal.__proto__===Animal.prototype; //true复制代码
Then we know that the __proto__
of animal
directly points to the prototype
of Animal
.
In addition, if we return a value in the function body of the constructor, let's see what happens:
function Animal(name){ this.name=name; return 1; }new Animal("test"); //Animal {name: "test"}复制代码
可以看到,直接无视了返回值,那我们返回一个对象试试:
function Animal(name){ this.name=name; return {}; }new Animal("test"); //{}复制代码
我们发现返回的实例对象被我们的返回值覆盖了,到这里大致了解了new
操作符的核心功能,我们做一个小结。
小结
new
操作符的作用:
- 创建一个新对象,将
this
绑定到新创建的对象 - 使用传入的参数调用构造函数
- 将创建的对象的
_proto__
指向构造函数的prototype
- 如果构造函数没有显式返回一个对象,则返回创建的新对象,否则返回显式返回的对象(如上文的
{}
)
模拟实现一个new操作符
说了这么多理论的,最后我们亲自动手来实现一个new
操作符吧~
var _myNew = function (constructor, ...args) { // 1. 创建一个新对象obj const obj = {}; //2. 将this绑定到新对象上,并使用传入的参数调用函数 //这里是为了拿到第一个参数,就是传入的构造函数 // let constructor = Array.prototype.shift.call(arguments); //绑定this的同时调用函数,...将参数展开传入 let res = constructor.call(obj, ...args) //3. 将创建的对象的_proto__指向构造函数的prototype obj.__proto__ = constructor.prototype //4. 根据显示返回的值判断最终返回结果 return res instanceof Object ? res : obj; }复制代码
上面是比较好理解的版本,我们可以简化一下得到下面这个版本:
function _new(fn, ...arg) { const obj = Object.create(fn.prototype); const res = fn.apply(obj, arg); return res instanceof Object ? res : obj;复制代码
大功告成!
总结
本文从定义出发,探索了new
操作符的作用目标和原理,并模拟实现了核心功能。其实模拟实现一个new
操作符不难,更重要的还是去理解这个过程,明白其中的原理。
更多相关免费学习推荐:javascript(视频)
The above is the detailed content of JavaScript: This time I completely understand the new operator!. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.