JS中 new究竟作了什麼?

若是寫了一個 new ,那麼 new 究竟作了什麼呢?

作了四件事:bash

  • 建立了一個空對象
  • 綁定this值
  • 連接到原型
  • 返回新對象

舉個栗子:app

function F(){

}

let o = new F();
複製代碼

四件事:
1.建立了一個對象 let o = {}
2.綁定this值 F.call(o)
3.連接到原型 o._ _ proto_ _ = F.prototype
4.返回新對象 return o函數

方法(function)簡寫後不支持new,箭頭函數也不支持new測試

模擬實現newui

function create(){
	//建立一個空對象  
	let obj = new Object();
	//獲取構造函數
	let Constructor = [].shift.call(arguments);
	//連接到原型
	obj.__proto__ = Constructor.prototype;
	//綁定this
	let result = Constructor.apply(obj,arguments);
	//返回新對象,(若是返回值是一個對象就返回該對象,不然返回構造函數的一個實例對象)
	return typeof result === "object" ? result : obj;
}
複製代碼

測試this

function Test(name,age){
	this.name = name;
	this.age = age;
}

let Test1 = new Test("Fan",20);
console.log(Test1.name);	// Fan
console.log(Test1.age);		// 20

let Test2 = create(Test,"Jun",22);
console.log(Test2.name);	// Jun
console.log(Test2.age);		// 22
複製代碼

經測試,create()可用spa

new的原理prototype

function Person(name){
    this.name = name;
    return {
    }
}
Person.prototype.say = function(){
    console.log("say....")
}
function myNew(){
    let Constructor = [].shift.call(arguments) 
    let obj = {};
    obj.__proto__ =  Constructor.prototype
    let r = Constructor.apply(obj,arguments)
    return r instanceof Object ? r : obj;
}
let p = myNew(Person,"Fan")
console.log(p.name)
p.say()
複製代碼

^_<

相關文章
相關標籤/搜索