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()
复制代码

^_<

相关文章
相关标签/搜索