盒子
盒子

模拟操作符、方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 模拟instanceof
function myInstanceof(left, right) {
var _prototype = right.prototype;
var _proto = left.__proto__;
while(true) {
if(_proto === null) return false;
if(_proto === _prototype) return true;
_proto = _proto.__proto__;
}
}

// 模拟new
function myNew(Constr) {
var obj = new Object();
obj.__proto__ = Constr.prototype;
var res = Constr.apply(obj, [...arguments].slice(1));
if(({}).toString.call(res) === '[object Object]') return res;
return obj;
}

// 模拟apply
Function.prototype.myApply = function(context = window) {
context.f = this;
var res = context.f(...arguments[1]);
delete context.f;
return res;
}

// 模拟call
Function.prototype.myCall = function(context = window) {
context.f = this;
var res = context.f(...[...arguments].slice(1));
delete context.f;
return res;
}

// 模拟bind
Function.prototype.myBind = function(context) {
var outerArgs = [...arguments].slice(1);
var f = this;
return function () {
var args = outerArgs.concat([...arguments].slice());
f.apply(context, args);
}
}
支持一下
扫一扫,支持 Alin
  • 微信扫一扫
  • 支付宝扫一扫