重写和重载
重载就是函数名一致,但是参数个数不同或类型不同
重写就是子类覆盖父类中的同一个方法,将其覆盖已达到重写的目的
载JavaScript中实现重写的几个思路:
1.重写原型对象
2.在实例中添加和原型中一样的函数,根据调用函数的规则:实例优先与原型调用
在JavaScript中实现重载的几个思路:
1.根据参数个数进行判断,然后调用不同的处理逻辑
2.使用闭包
实现重载
思路1:通过参数个数判断应该进行什么样的处理,
优点:代码清晰明了
缺点:可扩展性差1
2
3
4
5
6
7
8
9
10function add() {
let argLength = arguments.length;
if(argLength === 0) {
// 进行相应处理
}
else if(argLength === 1) {
// 进行相应处理
}
... // 可以接着进行判断、处理
}
思路2:通过闭包保存旧方法实现重写
优点:可扩展性好,可以动态的添加
缺点:仅实现参数个数不同的重写,未进行参数类型不同时的重写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
35function overloading(obj, methodName, fn) {
let oldMethod = obj[methodName]
obj[methodName] = function() {
if(fn.length === arguments.length) {
return fn.apply(this, arguments)
}
else if(typeof oldMethod === 'function') {
return oldMethod.apply(this, arguments)
}
}
}
var calculate = { a: 1, b: 2, c: 3}
overloading(calculate, 'add', function() { // 无参数的add方法
return 0
})
overloading(calculate, 'add', function(a) { // 有一个参数的add方法
return this[a]
})
overloading(calculate, 'add', function(a, b) { // 有两个参数的add方法
return this[a] + this[b]
})
overloading(calculate, 'add', function(a, b, c) { // 有三个参数的add方法
return this[a] + this[b] + this[c]
})
calculate.add() // 0
calculate.add('a') // 1
calculate.add('a', 'b') // 3
calculate.add('a', 'b', 'c') // 6