首頁  >  文章  >  web前端  >  JavaScript之 這次徹底搞懂new操作符!

JavaScript之 這次徹底搞懂new操作符!

coldplay.xixi
coldplay.xixi轉載
2020-09-27 17:30:371607瀏覽

JavaScript之 這次徹底搞懂new操作符!

前言

在學習JavaScript的過程中,不可避免的會遇到new操作子,這次就來好好刨根問底一下,也算是加深理解和記憶了。

什麼是new操作符?

mdn中是這麼定義new操作符的:

#new 運算子建立一個使用者定義的物件類型的實例或具有建構函數的內建對象的實例。

在這句話裡我們來看一個關鍵字:有建構子。這是個什麼意思呢?我們先透過幾個例子來看一下:

//例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复制代码

我們可以看到,例1成功的執行了new語句,創建出了實例。例2在new一個{}物件時報錯TypeError: TestObj is not a constructor,指出目標不是一個constructor。為什麼普通的物件就不能執行new操作符呢?在ECMA規範裡有相關的介紹:

If Type(argument) is not Object, return false.
If argument has a [[Construct]] internal method , return true. Return false.

意思就是:

  • 建構子首先得是一個對象,否則不滿足條件
  • 其次,物件必須擁有[[Construct]]內部方法,才可以當作建構子  

我們這裡的{}就是一個對象,滿足第一個條件,那麼顯然,肯定是因為{}沒有[[Construct]]這個內部方法,所以無法使用new運算符進行構造了。

那麼我們已經搞定了new操作符的可操作對象,是不是可以去看看它的作用了呢?答案是:NO!我們再來看一個例子:

//例3let testObj={
    Fn(){        console.log("构造成功!")
    }
}let t3=new testObj.Fn;//=>Uncaught TypeError: testObj.Fn is not a constructor复制代码

what?為什麼剛剛還能成功建構的函數,當方法就不行了?其實在MDN中也有直接介紹:

Methods cannot be constructors! They will throw a TypeError if you try to instantiate them.

意思就是,方法方法不能是建構子,如果嘗試建立一個方法的實例,就會拋出型別錯誤。這樣說就懂了,但是還沒完,這個說法沒有完全解釋清楚原理,我們再看個例子:

//例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复制代码

對照這個例子,我們在ECMA規範查閱,發現所有的函數在創建時都取決於FunctionCreate函數:

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".

這個函數的定義可以看出

  • 只有當型別為Normal的函式被創建時,它才是可建構的函數,否則他就是不可建構的。

在我們這個範例中,Arrow的型別為Arrow,而ShortHand的型別是 Method,因此都不屬於可建構的函數,這也解釋了例3所說的"方法不能作為建構子"。 搞清楚了new操作符可以操作的目標,終於可以神清氣爽的來看看它的作用了(不容易呀TAT)。

new運算子實現了什麼?

我們舉一個簡單的例子來具體看看它的作用:

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 animal=new Animal("大黄");复制代码

可以看到,執行new操作符後,我們得到了一個animal對象,那麼我們就知道,new操作符肯定要創建一個對象,並將這個對象返回。再看這段程式碼:

function Animal(name){    this.name=name;    console.log("create animal");
}复制代码

同時我們看到結果,確實輸出了create animal,我們就知道,Animal函數體在這個過程中被執行了,同時傳入了參數,所以才執行了我們的輸出語句。但我們的函數體裡還有一句this.name=name體現在哪裡呢?就是這一句:

console.log(animal.name);       //大黄复制代码

執行完函數體後,我們發現回傳物件的name#值就是我們賦值給this的值,那麼不難判斷,在在這個過程中,this的值指向了新建立的物件。最後還有一段:

Animal.prototype.say=function(){    console.log("myName is:"+this.name);
}
animal.say();                   //myName is:大黄复制代码

animal物件呼叫的是Animal函數原型上的方法,說明Animalanimal物件的原型鏈上,那麼在哪一層呢?讓我們驗證一下:

animal.__proto__===Animal.prototype; //true复制代码

那我們就知道了,animal__proto__直接指向了Animalprototype 。 除此之外,如果我們在建構函式的函式體裡回傳一個值,看看會怎麼樣:

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(视频)

以上是JavaScript之 這次徹底搞懂new操作符!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.im。如有侵權,請聯絡admin@php.cn刪除