-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbind.js
More file actions
43 lines (33 loc) · 1004 Bytes
/
bind.js
File metadata and controls
43 lines (33 loc) · 1004 Bytes
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
Function.prototype._bind = function(obj, ...args){
// fn为调用bind的函数
const fn = this;
// 新的this的值应该是一个对象,但是不能是null
if(typeof obj !== "object" || obj === null) return undefined;
function bound(...restArgs) {
const _this = this;
// _this instanceof bound
// 如果这个bound函数被当作构造器调用
if(new.target){
// 被当作构造函数调用
fn.call(_this, ...args, ...restArgs);
Object.setPrototypeOf(_this, fn.prototype);
return _this;
} else {
return fn.call(obj, ...args, ...restArgs);
}
}
return bound;
}
function Person(name, age){
this.name = name;
this.age = age;
}
let obj = {
height: 180
};
let _person = Person._bind(obj, "hhn");
_person(21);
// bind返回的函数配合new一起使用,则忽略之前绑定的this
let o = new _person(22);
console.log(obj);
console.log(o);