函数重载
什么事函数重载呢?当我们多次调用函数时传递不同参数数量或者类型,函数会做出不同处理。
1、函数签名
这里介绍个名次「函数签名」,顾名思义,函数签名主要定义了参数及参数类型,返回值及返回值类型。函数签名不同,函数会做出不同的处理,这是我对函数重载的理解。
2、构造器重载
举个例子,声明一个类Course,里面写一个begin的方法,我们调用 begin时传入不同参数类型已经参数个数,begin方法会做出不同处理,那么怎么实现呢?具体如下:
type Combinable = number | string;
class Course {
//定义重载签名
begin(name: number, score: number): string;
begin(name: string, score: string): string;
begin(name: string, score: number): string;
begin(name: number, score: string): string;
//定义实现签名
begin(name: Combinable, score: Combinable) {
if (typeof name === 'string' || typeof score === 'string') {
return 'student:' + name + ':' + score;
}
}
}
const course = new Course();
course.begin(111, 5);//没有输出
course.begin('zhangsan', 5);//student:zhangsan:5
course.begin(5, 'zhangsan');//student:5:zhangsan
以上代码中定义了4个重载前面和1个实现签名。
3、联合类型函数重载
声明一个函数arithmetic,参数类型为联合类型,返回值也是联合类型,但是如下代码却报错了。
function arithmetic(x: number | string): number | string {
if (typeof x === 'number') {
return x;
} else {
return x+'是字符串';
}
}
arithmetic(1).length;
原因是没有明确函数string类型没有toFixed属性`,那么怎么用函数重载解决这个报错问题呢?
我们可以可以根据传参的类型和函数返回值声明多个同名的函数,只是类型和返回值不同而已。
function arithmetic(x: number): number;
function arithmetic(x: string): string;
function arithmetic(x: number | string): number | string {
if (typeof x === 'number') {
return x;
} else {
return x+'是字符串';
}
}
arithmetic(1).toFixed(1);
这样就不会报错啦,因为已经识别到arithmetic(1)的返回值是number类型。
拓展JS中函数重载
JS中函数重载怎么实现呢?
1、利用arguments参数
var arr = [1,2,3,4,5];
//注意:这里不能写成箭头函数,否则this指向的是window对象
Array.prototype.search = function() {
var len = arguments.length;
switch(len){
case 0:
return this;
case 1:
return `${arguments[0]}`;
case 2:
return `${arguments[0]},${arguments[1]}`;
}
}
console.log(arr.search()) //[1,2,3,4,5]
console.log(arr.search(1)) //1
console.log(arr.search(1,2)) //1,2
2、利用闭包和arguments
function addMethod (obj, name, fn) {
var old = obj[name];
obj[name] = function () {
if (fn.length === arguments.length) {
return fn.apply(this, arguments)
} else if (typeof old === 'function') {
return old.apply(this, arguments)
}
}
}
var person = {name: 'zhangsan'}
addMethod(person, 'getName', function () {
console.log(this.name + '---->' + 'getName1')
})
addMethod(person, 'getName', function (str) {
console.log(this.name + '---->' + str)
})
addMethod(person, 'getName', function (a, b) {
console.log(this.name + '---->' + (a + b))
})
person.getName()
person.getName('zhangsan')
person.getName(10, 20)