JS中 new究竟做了什么?

2,154 阅读1分钟

文章已同步至【个人博客】,欢迎访问😃
文章地址:blog.fanjunyang.zone/archives/js…

如果写了一个 new ,那么 new 究竟做了什么呢?

做了四件事:

  • 创建了一个空对象
  • 绑定this值
  • 链接到原型
  • 返回新对象

举个栗子:

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

模拟实现new

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;
}

测试

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()可用

new的原理

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

^_<