apply与call的用法实例解析

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// apply与call的基本用法
function add(a, b) {
return a + b
}

function sub(a, b) {
return a - b
}

var a1 = add.apply(sub, [42, 23]);
var a2 = sub.apply(add, [32, 10]);
console.log(a1);//65
console.log(a2);//22
var a3 = add.call(sub, 3, 2);
console.log(a3);//5
//实现继承
function Animal(name) {
this.name = name;
this.showName = function () {
console.log(this.name)
}
}
;
function Cat(name) {
Animal.apply(this, [name]);
}
;
var cat = new Cat('西系咪');
cat.showName();
//call方法Animal.call(this,name)
//多重继承
function Class1() {
this.showSub = function (a, b) {
console.log(a - b);
}
}

function Class2() {
this.showAdd = function (a, b) {
console.log(a + b)
}
}
;

function Class3() {
Class1.apply(this);
Class2.apply(this);//表示当前对象分别调用了Class10的方法和调用了Class11的方法
}
;
var c = new Class3();
c.showSub(3, 1);//2
c.showAdd(3, 1)//4

</script>
</body>
</html>
原文地址:https://www.cnblogs.com/johnny-cli/p/7605492.html