ES5实现原生/ES6方法
实现 bind apply call 方法
实现call
Function.prototype.myCall = function (context, ...args) {
context = context || window;
// 这里使用fn可能存在context已有对应属性,不严谨,可以使用Symbol对象生成唯一属性key
context.fn = this;
const res = context.fn(...args);
delete context.fn;
return res;
}实现apply
Function.prototype.myApply = function (context, args) {
context = context || global;
// 这里使用fn可能存在context已有对应属性,不严谨,可以使用Symbol对象生成唯一属性key
context.fn = this;
const res = context.fn(...args);
delete context.fn;
return res;
}实现bind
bind 返回一个原函数的拷贝,并拥有指定的this值和初始参数。
因此需要存储一下 初始参数,调用的时候,将初始参数和传入的参数合并
测试方法可以参考DEMO/JS
instanceOf 实现
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
Json.stringify Json.parse实现
遍历对象,将对象转换为字符串,需要对 null boolean null undefined 特殊判断
通过递归的方式,将字符串转换为对象,其中null boolean undefined 需要转化为对应的值
Last updated