function Animal(name) {
this.name = name
this.showName = function () {
console.log(this.name)
}
}
function Cat(name) {
// Cat调用Animal方法,同 Animal.call(this, name)
Animal.apply(this, [name])
}
var cat = new Cat(‘小猫’)
cat.showName()
输出:
小猫
多重继承
function Func1() {
this.sub = function (a, b) {
console.log(a - b)
}
}
function Func2() {
this.add = function (a, b) {
console.log(a + b)
}
}
function Func3() {
// Func3调用Func1方法,同 Func1.call(this)
Func1.apply(this)
// Func3调用Func2方法,同 Func2.call(this)
Func2.apply(this)
}
var func = new Func3()
func.sub(1, 2)
func.add(1, 2)
输出:
-1
3
apply妙用1
var numbers = [5, 6, 1, 3, 7];
var max = Math.max.apply(null, numbers)
console.log(max)
var min = Math.min.apply(null, numbers)
console.log(min)
输出:
7
1
Math.max()方法,只能传递参数列表Math.max(param1, param2…),不支持Math.max([ 《大厂前端面试题解析+Web核心总结学习笔记+企业项目实战源码+最新高清讲解视频》无偿开源 徽信搜索公众号【编程进阶路】 param1, param2]) 。借助apply,我们可以将一个数组参数转换为一个参数列表([param1, param2…] 转换为 (param1,param2…)
apply妙用2
var arr1 = new Array(“1”,“2”,“3”)
var arr2 = new Array(“4”,“5”,“6”)
// push返回数组长度
Array.prototype.push.apply(arr1, arr2) // 等价于arr1.push(“4”,“5”,“6”)
console.log(arr1)
输出:
6
[“1”, “2”, “3”, “4”, “5”, “6”]
与君共勉:再牛逼的梦想,也抵不住傻逼般的坚持!