0%

手写一些API

手写一些方法

instanceof

1
2
3
4
5
6
function _instanceof(left, right) {
if (left.__proto__ === null || left.__proto__ === undefined) return false;
return left.__proto__ === right.prototype
? true
: _instanceof(left.__proto__, right);
}

new

1
2
3
4
5
6
function factory(fn, ...args) {
let o = {};
o.__proto__ = fn.prototype;
fn.call(o, ...args);
return o;
}

call

1
2
3
4
5
6
7
8
9
10
11
12
Function.prototype._call = function(context, ...args) {
if (typeof this !== "function") {
throw new TypeError(
"Function.prototype._call - what is trying to be bound is not callable"
);
}
const ctx = context || window;
ctx.fn = this;
const result = ctx.fn(...args);
delete ctx.fn;
return result;
};

apply

1
2
3
4
5
6
7
8
9
10
11
12
Function.prototype._apply = function(context, ...args) {
if (typeof this !== "function") {
throw new TypeError(
"Function.prototype._apply - what is trying to be bound is not callable"
);
}
const ctx = context || window;
ctx.fn = this;
const result = ctx.fn(...args[0]);
delete ctx.fn;
return result;
};

bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function.prototype._bind = function(context, ...args) {
const ctx = context || window;
const _this = this;
function fn() {}
function result(...argus) {
return _this.apply(this instanceof result ? this : ctx, [
...args,
...argus
]);
}
if (this.prototype) {
fn.prototype = this.prototype;
}
result.prototype = new fn();
return result;
};