第14題 - new操做符內部實現原理

面試題目:

new 操做符內部實現原理是什麼?前端

答案解析:

new 操做符常常被用到,用面嚮對象語言們通用的觀點來看:new 是用來實例化一個類,從而在內存中分配一個實例對象。面試

new 關鍵字會進行以下操做:bash

  1. 建立一個空的JavaScript對象(即{});
  2. 將函數的 prototype 賦值給對象的 __proto__屬性 ;
  3. 調用函數,並將步驟1新建立的對象做爲函數的this上下文 ;
  4. 若是該函數沒有返回值或者返回值不是對象,則返回建立的對象,若是返回值是對象,則直接返回該對象。

示例:函數

function Person(name) {
    this.name = name;
}
function Person2(name) {
    this.name = name;
    return this.name;
}
function Person3(name) {
    this.name = name;
    return new Array();
}
function Person4(name) {
    this.name = name;
    return new String(name);
}
function Person5(name) {
    this.name = name;
    return function() {};
}


var person = new Person('John');  // {name: 'John'}
var person2 = new Person2('John');  // {name: 'John'}
var person3 = new Person3('John');  // []
var person4 = new Person4('John');  // 'John'
var person5 = new Person5('John');  // function() {}
複製代碼

Person自己是一個普通函數,當經過new來建立對象時,Person就是構造函數了。ui

JS引擎執行這句代碼時,在內部作了不少工做,用僞代碼模擬其工做流程以下:this

new Person("John") = {
    var obj = {};
	obj.__proto__ = Person.prototype; // 此時便創建了obj對象的原型鏈: obj->Person.prototype->Object.prototype->null
	var result = Person.call(obj,"John"); // 至關於obj.Person("John")
	return typeof result === 'object' ? result : obj; // 若是無返回值或者返回一個非對象值,則將obj返回做爲新對象
}
複製代碼

延伸

原型鏈是面試中必考題目,new 和原型鏈常常一塊兒出現,看下面這道題目:spa

function Parent(name) {
    this.name = name;
}

var child = new Parent('前端名獅');
console.log(Parent.prototype); // {constructor: function Parent(name){this.name = name}}
console.log(child.prototype); // undefined
複製代碼

JavaScript 中,萬物皆對象!但對象也是有區別的。分爲普通對象和函數對象,Object ,Function 是JS自帶的函數對象。 函數對象會預約義一個屬性就是原型對象prototype。注:普通對象沒有prototype,但有__proto__屬性。prototype

Parent是函數對象,Parent.prototype是存在的。code

由上面的new 操做符的工做原理,咱們知道它返回的是一個普通對象{},因此它是沒有prototype屬性的,輸出undefinedcdn


掃一掃 關注個人公衆號【前端名獅】,更多精彩內容陪伴你!

【前端名獅】
相關文章
相關標籤/搜索