今天无意看到 function有个apply的函数于是就去看看 发现很好玩 在这里分享下 先看看参数
apply方法能劫持另外一个对象的方法,继承另外一个对象的属性
Function.apply(obj,args)方法能接收两个参数
obj:这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args-->arguments)
--args的数组就会一个个的变成那个方法的参数
好啦 现在来看看apply的用法
1)使用apply来简单实现js的继承 上代码
function Person(name){
this.name= name,
this.eat= function(){
document.writeln(this.name);
}
}
function child (name,age){
Person.apply(this,arguments),
this.age=age
}
child.prototype.fly= function(where){
document.writeln(where)
} ;
var a = new child("pc",12);
a.fly(" house") ;
a.eat("sweet ")
输出结果
house pc
class child是没有eat方法的使用apply就可以简单的实现继承
=====================分割线=============================
要注意的是Person如果使用prototype的方法不能被继承? 上代码吧
function Person(name){
this.name= name
}
Person.prototype.eat=function(food){
document.writeln(this.name);
} ;
function child (name,age){
Person.apply(this,arguments),
this.age=age
}
child.prototype.fly= function(where){
document.writeln(where);
} ;
var a = new child("pc",12);
a.fly(" house") ;
a.eat("sweet ")
运行后 只会输出 house
所以使用apply来实现的时候要注意方法写在Person里面
2)使用apply的arg写出优雅的代码 如
1.
var a = Math.min(1,3,7,2,8,8);
document.writeln(a); //1
但是如果我要求出一个数组的的min呢 难道要写循环? apply 帮您解决
var a = [1,3,7,2,8,8] ;
var b=Math.min.apply(null,a) ;
document.writeln(b); //1
2.
var arr1=[1,2,3];
var arr2 = [4,5,6] ;
arr1.push(arr2);
console.log(arr1);
这样就会出现 [1,2,3,[4,5,6]] apply也可以解决
var arr1=[1,2,3];
var arr2 = [4,5,6] ;
arr1.push.apply(arr1,arr2);
console.log(arr1);//[1,2,3,4,5,6]
也可以这样写
var arr1=[1,2,3];
var arr2 = [4,5,6] ;
Array.prototype.push.apply(arr1,arr2)
console.log(arr1);<span style="font-family: Arial, Helvetica, sans-serif;">//[1,2,3,4,5,6]</span>