new Animal('cat') = { var obj = {};//创建空对象 obj.__proto__ = Animal.prototype;//链接原型链 var result = Animal.call(obj,"cat");//改变this指向 return typeofresult ==='object'? result : obj;//返回值是 }
了解new的内部工作原理,看看下面几种情况:
1 2 3 4 5 6 7
functionfn() { this.user = '追梦子'; return {}; //这里返回一个空对象 } var a = new fn; // a时空对象 console.log(a.user); //undefined
1 2 3 4 5 6
functionfn() { this.user = '追梦子'; //无返回值 } var a = new fn; // fn无返回值 console.log(a.user); //追梦子
const myCall = function (context) { context.fn = this let args = Array.from(arguments).slice(1) //Array.from 把伪数组对象转为数组 let result = context.fn(...args) delete context.fn return result }