-
Notifications
You must be signed in to change notification settings - Fork 1
/
bind.html
55 lines (55 loc) · 1.19 KB
/
bind.html
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
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body></body>
<script type="text/javascript">
class Animal {
constructor() {
this.type = 'animal'
}
says(say) {
setTimeout(function () {
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
}
}
var animal = new Animal();
animal.says('hi') //undefined says hi
//bind 实现原理
Function.prototype.Bind = function (context) {
var self = this
return function () {
var arg = [...arguments][0]
self.call(context, arg)
}
}
Function.prototype._bind = function (context) {
let self = this
let args_1 = Array.prototype.slice.call(arguments, 1)
console.log(args_1)
return function (t) {
let args_2 = Array.prototype.slice.call(arguments)
console.log(args_2)
let args = args_1.concat(args_2)
console.log(args)
return self.apply(context, args)
}
}
var obj = {
a: 3,
test: function (t, l) {
console.log(this.a, t)
// return function(q){ console.log(q) }
console.log(++l)
}
}
//obj.test()
var a = 4;
//obj.test.Bind(window,10)
var t = obj.test._bind(window)
t(2, 10)
//obj.test.bind(window,10)()(4)
</script>
</html>