手写Call
Function.prototype.MyCall = function(context){
var context = context ?? window;
let fnSymbol = Symbol();
context[fnSymbol] = this;
const arg = [...arguments].slice(1);
let res = context[fnSymbol](...arg);
delete context[fnSymbol]
return res;
}
const obj = {
name: '123',
}
function bar(gender,age){
// 函数有返回值==》需要返回
return {
name:this.name,
gender,
age
}
}
console.log(bar.MyCall(obj,['男',46]));
手写bind
const obj = {
name: '刘德华'
}
const person = function () {
//该fn做为构造函数使用,此时的name为undefined
console.log(this.name)
console.log(arguments, 'arguments')
}
person.prototype.friend = '123123'
Function.prototype.myBind = function (context, ...args) {
const _this = this;
const tempFun = function(){}
const fn = function (...returnArgs) {
_this.apply(this instanceof fn ? this : context, [...args, ...returnArgs])
}
tempFun.prototype = this.prototype;
fn.prototype = new tempFun();
return fn
}
const fn = person.myBind(obj, 1, 2)
const bibi = new fn()
// 此时需要将person.prototype 与 bibi 串联起来
标签:function,...,const,bind,Call,context,手写,prototype,fn
From: https://www.cnblogs.com/crazy-rock/p/17904781.html