Home  >  Article  >  Web Front-end  >  JavaScript: This time I completely understand the new operator!

JavaScript: This time I completely understand the new operator!

coldplay.xixi
coldplay.xixiforward
2020-09-27 17:30:371605browse

JavaScript: This time I completely understand the new operator!

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 FunctionCreateFunction:

FunctionCreate (kind, ParameterList, Body, Scope, Strict, prototype)

  1. If the prototype argument was not passed, then let prototype be the intrinsic object %FunctionPrototype%.
  2. 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 animalOn 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!

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