Function.prototype.myapply=function(content) {
var res;
//console.log(this);
if(typeof this != "function"){
console.log("not a function");
}else{
content = content || window; //es6默认参数 有参数取content,无参数取window
content.fn = this; //apply第一个参数为this要重新指向的对象
if(arguments[1]) { //如果有后续参数
res = content.fn(arguments[1]);
} else{
res = content.fn();
}
}
delete content.fn; //不删除会导致实例化的对象多了一个fn的函数,在该例子中,fn为Parent()
return res;
}
function Parent(work){
this.work = work;
}
function Child(name,work){
this.name = name;
Parent.myapply(this,work);
}
var child = new Child("张三","工人");
console.log(child,child.work,child.name);
手写实现apply函数
最新推荐文章于 2024-06-09 22:26:02 发布