-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.js
More file actions
82 lines (67 loc) · 2.36 KB
/
bind.js
File metadata and controls
82 lines (67 loc) · 2.36 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Function.prototype.bind1 = function(bindObj) {
let self = this;
let args = [...arguments].slice(1);// 取1及后面的数
return function(...rest) {
return self.apply(bindObj, args.concat(rest));
}
}
Function.prototype.bind8 = function(bindObj) {
let self = this;
let args = [...arguments].slice(1);// 取1及后面的数
return function(...rest) {
return self.apply(bindObj,args.concat(rest))
}
}
// ----------------------------------------------------------------
// 当前版本可以优化的地方:bind返回的函数可以作为构造函数调用,new 构造返回的对象的this默认指向的是构造函数的prototype
Function.prototype.bind2 = function(context,...rest) {
let self = this;
const fFound = function(...args) {
// 如果是构造函数调用,返回对象的原型会指向构造函数的prototype
// 判断返回的对象的this 的原型链上是不是有fFound,如果有,说明是new 构造函数出来的
return self.apply(this instanceof fFound? this:context,rest.concat(args))
}
return fFound;
}
//----------------------------------------------------------------
// 当前版本的问题: 返回的对象的并没有实现原型继承
Function.prototype.bind3 = function(context, ...rest) {
let self = this;
const fFound = function(...args) {
return self.apply(this instanceof fFound? this: context,rest.concat(args));
}
Object.setPrototypeOf(fFound, this.prototype);
return fFound;
}
Function.prototype.bind4 = function(context,...rest) {
let self = this;
const fFound = function(...args) {
return self.apply(this instanceof fFound? this:context,rest.concat(args));
}
Object.setPrototypeOf(fFound, this.prototype);
return fFound;
}
Function.prototype.bind5 = function(context, ...rest) {
const self = this;
const fFound = function(...args) {
let obj = this instanceof fFound ? this : context;
return self.apply(obj,rest.concat(args));
}
Object.setPrototypeOf(fFound, this.prototype);
return fFound;
}
var name = 'Jack';
var Yve = {
name: 'Yvette'
};
function person(age, job, gender) {
this.work = '福报'; // 实例属性
console.log(this.name, age, job, gender);
}
person.prototype.clockIn = function () {
console.log(996);
}
var bindYve = person.bind3(Yve, 22, 'engineer');
var obj = new bindYve('female');
obj.work; // 福报
obj.clockIn(); // 996