new操做符实现原理:
function news(func) {
var target = {};//生成新对象
target.__proto__ = func.prototype;//实例的__proto__指向原型,构造函数的prototype也指向原型(连接到原型)
var res = func.call(target);//把函数的this绑定在了新生成的对象中
if (typeof (res) == "object" || typeof (res) == "function") {
return res;//若是传入的函数(构造函数)有本身的返回值,则返回该值
}
return target;//若是若是传入的函数(构造函数)没有本身的返回值,则返回新对象
}
若是暂时看不明白,请往下看:函数
1.明白new的原理首先咱们须要明白原型,构造函数,实例的关系this
写明是栗子,以函数Father为例,函数Father就是一个构造函数,咱们能够经过它构建一个实例spa
function Father() {
let colors = [1,2,3];
return colors;
}
const instance = new Father();
此时,instance为实例,构造函数为Father,构造函数拥有一个prototype的属性指向原型。prototype
所以原型为:code
const prototype = Father.prototype;
所以看得出三者的关系:对象
实例.__proto__===原型
原型.constructor === 构造函数
构造函数.prototype === 原型
实例.constructor === 构造函数
例子:blog
function instanceFun(){
this.colors=['res','pink','black']
}
const instance = new Father();
console.log(instanceFun.prototype.constructor,'构造函数');
console.log(instance.__proto__,'实例访问原型');
console.log(instanceFun.prototype,'构造函数访问原型');
console.log(instance.constructor,'实例的构造函数');
2.new运算符的执行过程继承