new 操做符內部實現原理是什麼?前端
new
操做符常常被用到,用面嚮對象語言們通用的觀點來看:new
是用來實例化一個類,從而在內存中分配一個實例對象。面試
new
關鍵字會進行以下操做:bash
JavaScript
對象(即{}
);prototype
賦值給對象的 __proto__
屬性 ;this
上下文 ;示例:函數
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
屬性的,輸出undefined
cdn
掃一掃 關注個人公衆號【前端名獅】,更多精彩內容陪伴你!