Function.prototype.myCall = function(context){
//this指向调用myCall的函数
if(typeof this !== 'function'){
console.log("not function!");
return;
}
context = context || window;
context.fn = this;
//arguments是Object类型
const args = [...arguments].slice(1);
const result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myApply = function(contex){
if(typeof this !== 'function'){
throw new TypeError('not function!');
return;
}
context = context || window;
context.fn = this;
let result;
if(arguments[1]){
result = context.fn(...arguments[1]);
}else{
result = context.fn();
}
delete context.fn;
return result;
}
function Person(name,age){
this.name = name;
this.age = age;
this.info = function(){
return 'My name is ' + this.name + " ,I'm " + this.age;
}
}
function Student(name,age,gender){
Person.myCall(this,name,age,gender);
//Person.myApply(this,[name,age,gender]);
this.gender = gender;
}
const stu = new Student('Evey','18','girl');
alert(stu.info());// My name is Evey, I'm 18
手写call、apply函数
最新推荐文章于 2024-04-07 21:09:54 发布