先看普通的构造函数
function Person(name,age) { this.name=name; this.age=age; }
其实在new的过程中内部实现了隐式创建对象
function Person(name,age) { //this={};隐式执行让this等于一个对象 this.name=name; this.age=age; //return this 隐式返回了this } new Person;
下面来写一个函数来实现new的作用
function Animal(name,sex) { this.name=name; this.sex=sex; } Animal.prototype.call=function (){ console.log('I am a '+this.name+',and I am a '+this.sex) } function newObj(obj,...rest) { const newObj={};//创建新对象 newObj.__proto__=Animal.prototype;//让对象的原型指向Animal构造函数 Animal.apply(newObj,rest);//让构造函数的this指向新的对象,并传递参数 return newObj } const obj1=newObj(Animal,'老虎','male'); const obj2=newObj(Animal,'狐狸','female');