本质就是将原型链与实例的this联系起来,this指向的是这个新对象,同时也指向这个构造函数。
function Person(){this.name=name;this.age=age;this.sayName=function(){return this.name;}}let person=new Person("mickey",23);console.log(person.sayName);
- 首先利用字面量的方式创建了一个对象实例,比如let person={};
- 紧接着将对象实例的proto属性指向构造函数的原型对象,即:person.proto=Person.prototype
- 再接着改变this的指向为新对象,即将构造函数的作用域赋值给新的对象
- 然后执行构造函数里面的代码,将属性添加给person中的this的对象
- 返回新的对象person
let person={}person.__proto__=Person.prototype//引用构造函数的原型对象Person.call(person) //将构造函数的作用域赋值给person,即this执行person具体实现方式如下:Function.methods("new",function(){let that=Object.create(this.prototype); // 新创建一个新对象,他继承了构造器的原型对象,即此时that的__proto__指向的是this.prototypelet other=this.apply(that,argument); // 调用构造器绑定this对象到新的对象that上,即改变this的指向return (typeof other==="object"&&other)||that; // 如果它的返回值不是一个对象的话,就返回新的对象})
