手动实现bind

本文最后更新于:2023年3月19日 晚上

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
Function.prototype.myBind = function (context, ...args) {
const fn = this;
const bound = function (...args2) {
const newArgs = [...args, ...args2];
// 如果是new方法调用,this指向bound实例化对象,则使用该方式执行一次构造方法
// 如果是普通调用,this指向window
if (this instanceof bound) {
fn.apply(this, newArgs);
} else {
fn.apply(context, newArgs);
}
};
// 处理new的情况,如果简单绑定原型,会导致修改实例的__proto__会修改Person的原型
// bound.prototype=fn.prototype
// 下面的代码,其实是一种原型链继承方式
Object.setPrototypeOf(bound.prototype, fn.prototype);
return bound;
};

function getName() {
console.log(this.name);
console.log(...arguments);
}

function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
console.log(this.name);
};

let test = Person.myBind({}, 123);
let test2 = new test(789);
test2.__proto__.getName = function () {
console.log("被篡改");
};
Person.prototype.getName();

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!