-
Notifications
You must be signed in to change notification settings - Fork 0
/
自动绑定实例方法.html
70 lines (62 loc) · 1.95 KB
/
自动绑定实例方法.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>自动绑定实例方法</title>
</head>
<body>
<p>在 JavaScript 的类当中,类实例如果不通过实例进行调用,方法中的 this 就不会指向实例,例如:</p>
<pre>
class Person {
constructor (name) {
this.name = name
}
sayHi () {
console.log(`I am ${this.name}.`)
}
}
const jerry = new Person('Jerry')
const sayHi = jerry.sayHi
sayHi() // => 报错
</pre>
<p>
所以在类似于 React.js 的组件的事件监听当中我们总是需要手动地进行 bind(this) 操作。为了简化这样的操作,请你完成一个方法 autoBind,它可以接受一个类作为参数,并且返回一个类。返回的类的实例和原来的类的实例功能上并无差别,只是新的类的实例所有方法都会自动 bind
到实例上。例如:
</p>
<pre>
const BoundPerson = autoBind(Person)
const jerry = new BoundPerson('Jerry')
const sayHi = jerry.sayHi
sayHi() // => I am Jerry.
const lucy = new BoundPerson('Lucy')
const sayHi = lucy.sayHi
sayHi() // => I am Lucy.
</pre>
<p>注意,如果 autoBind 以后给原来的类新增方法,也会自动反映在实例上,例如:</p>
<pre>
Person.prototype.sayGood = function () {
console.log(`I am ${this.name}. I am good!`)
}
const sayGood = lucy.sayGood
sayGood() // => I am Lucy. I am good!
</pre>
<p>请你完成 autoBind 的编写。</p>
<script>
class Person {
constructor(name) {
this.name = name
}
sayHi() {
console.log(`I am ${this.name}.`)
}
}
const jerry = new Person('Jerry')
const sayHi = jerry.sayHi
// sayHi() // => 报错
const autoBind = (ToBindClass) => {
}
</script>
</body>
</html>