網(wǎng)站集約化建設(shè)紀(jì)要網(wǎng)站案例分析
在js中我們經(jīng)常會使用到new關(guān)鍵字,那我們在使用new關(guān)鍵字的時候,new到底做了什么呢?今天我們就來深入探究一下
1.初步使用
我們先來使用一下,這是一個正常操作
function Person() {this.name = "John";}let person = new Person();console.log(person.name); // John
new關(guān)鍵字主要做了這幾件事情:
????1.創(chuàng)建一個新對象
? ? 2.將構(gòu)造函數(shù)的作用域賦值給新對象(this指向新對象)
? ? 3.執(zhí)行構(gòu)造函數(shù)中的代碼
? ? 4.返回新對象
2.不使用new
那我們不使用new關(guān)鍵字,又會發(fā)生什么?
function Person1() {this.name = "John1";}let p1 = Person1();console.log(p1); //undefinedconsole.log(name); //name this指向window,所以輸出John1
?3.構(gòu)造函數(shù)有return
function Person2() {this.name = "mike";return { age: 18 };}let p2 = new Person2();console.log(p2); //{age: 18}console.log(p2.name); //undefined
如果構(gòu)造函數(shù)返回一個對象,new命令會直接返回這個return的對象
如果return的不是一個對象,那還是回按照new的實現(xiàn)步驟,返回實例對象
?4.手動實現(xiàn)new關(guān)鍵字
function _new(fn, ...args) {if (typeof fn !== "function") {throw "fn must be a function";}// 創(chuàng)建一個對象,其對象的原型,指向構(gòu)造函數(shù)的原型對象let obj = Object.create(fn.prototype);let res = fn.apply(obj, ...args);return res instanceof Object ? res : obj// 構(gòu)造函數(shù)本身如果返回的是對象的話,則 返回的就是此對象// 如果返回值不是對象的話,則 返回對應(yīng)的objreturn isObject || isFunction ? res : obj;}function Ele() {this.name = "Ele";}let e = _new(Ele)console.log(e.name); // Ele
如果你覺得本文對你有所幫助,歡迎評論,點贊與關(guān)注,一起卷~