bind
// Test case
function show(){
console.log(this.name, this.age);
console.log(arguments[0]);
}
show.myBind({ name: "coco", age: 18 }, 'female')(); // should show coco, 18 female
Function.prototype.myBind = function(context){
const _this = this;
const args = Array(...arguments).slice(1);
return function(){
return _this.apply(context, [...arguments, ...args])
}
}
call
// Test case
function show(gender){
console.log(this.name, this.age, gender);
}
show.myCall({ name: "coco", age: 18 }, 'female'); // should show coco, 18, female
Function.prototype.myCall = function(){
const [context, ...args] = Array(...argument);
const result = context.fn(...args);
delete context.fn;
return result;
}
apply
// Test case
function show(gender){
console.log(this.name, this.age, gender);
}
show.myApply({ name: "coco", age: 18 }, 'female'); // should show coco, 18, female
Function.prototype.myApply = function(){
const [context, args] = Array(...argument);
const result = context.fn(...args);
delete context.fn;
return result;
}
new
// Test case
function Person(name){
this.name = name
}
const person = myNew(Person, "coco")
console.log(person.name);
console.log(person.__proto__ === Person.prototype)
function muNew(constructer){
let obj = {};
const args = Array(arguments).slice(1);
constructer.apply(obj, args);
obj.__proto__ = constructer.prototype;
return obj;
}
网友评论