function myNew(fn,args){
var obj = {}
obj.__proto__ = fn.prototype
//创建实例的时候传参
var res = fn.apply(obj,args)
//当构造函数有return时,返回return值,没有则返回obj{}
return res instanceof Object ? res : obj
}
function returnObj(age){
this.age = age
return {
name:'tes'
}
}
function fn(age){
this.age = age
}
var obj = myNew(returnObj,[1])
console.log(obj); // { name: 'tes' }
var obj = myNew(fn,[1])
console.log(obj); // fn { age: 1 }
function myAppy(obj,args){
obj.fn = this;
obj.fn(...args)
delete obj.fn
}
let obj = {
age: 1
}
function fn(a){
console.log(this.age);
console.log(a);
}
Function.prototype.myAppy = function(obj,args){
obj.fn = this;
obj.fn(...args)
delete obj.fn
}
fn.myAppy(obj,[2]) // 1 2