apply 方法很强大,可以用来实现类似面向对象编程的特性。
实现继承:
function Person(){
this.a = 'person';
this.b = function(){
alert('I\'m a person!');
}
}
function Student(){
Person.apply(this,arguments);
this.a = 'student';
this.c = 'Student class';
this.b = function(){
alert('I\'m a Student');
}
this.d = function(){
alert('This is Student\'s function.');
}
}
function main(){
var student = new Student();
student.b();
alert(student.a);
alert(student.c);
student.d();
}
main();
注意,如果在Student()中,将
Person.apply(this,arguments);移到函数尾,则结果大不一样,象这样:
function Student(){
this.a = 'student';
this.c = 'Student class';
this.b = function(){
alert('I\'m a Student');
}
this.d = function(){
alert('This is Student\'s function.');
}
Person.apply(this,arguments);
}
Person 中的属性和方法会覆盖掉Student的属性和方法。
说明,下面的参考文章关于数组的push.apply()验证
arr1.push(arr2)显然是不行的。 因为这样做会得到[1,3,4,[3,4,5]]
Array.prototype.push.apply(arr1,arr2) 结果:arr1=[1,3,4,3,4,5]
var arr1=[1,3,4];
var arr2=[3,4,5];
function test1(obj){
var arrLen=arr2.length;
for(var i=0;i<arrLen;i++){
arr1.push(arr2[i]);
}
}
function main(){
//test1();
//Array.prototype.push.apply(arr1,arr2);
//arr1.push(arr2);
for(var i=0;i<arr1.length;i++){
alert(i + '=' + arr1[i]);
}
alert(arr1.join(','));
}
参考文章:
js中apply方法的使用
1、对象的继承,一般的做法是复制:Object.extend
prototype.js的实现方式是:
| } |
除此之外,还有种方法,就是:Function.apply(当然使用Function.call也是可以的)
apply方法能劫持另外一个对象的方法,继承另外一个对象的属性
Function.apply(obj,args)方法能接收两个参数
apply示范代码如下:
| <script> function Person(name,age){ } function Print(){ } function Student(name,age,grade,school){ } var p1=new Person("jake",10); p1.sayhello(); var s1=new Student("tom",13,6,"清华小学"); s1.show(); s1.sayhello(); alert(s1.funcName); </script> |
学生类本来不具备任何方法,但是在Person.apply(this,arguments)后,
他就具备了Person类的sayhello方法和所有属性。
在Print.apply(this,arguments)后就自动得到了show()方法
2、利用Apply的参数数组化来提高
Function.apply()在提升程序性能方面的技巧
我们先从Math.max()函数说起,Math.max后面可以接任意个参数,最后返回所有参数中的最大值。
比如
alert(Math.max(5,8))
alert(Math.max(5,7,9,3,1,6))
但是在很多情况下,我们需要找出数组中最大的元素。
var arr=[5,7,9,1]
alert(Math.max(arr))
function getMax(arr){
}
这样写麻烦而且低效。如果用 apply呢,看代码:
function getMax2(arr){
}
两段代码达到了同样的目的,但是getMax2却优雅,高效,简洁得多。
再比如数组的push方法。
var arr1=[1,3,4];
var arr2=[3,4,5];
如果我们要把 arr2展开,然后一个一个追加到arr1中去,最后让arr1=[1,3,4,3,4,5]
arr1.push(arr2)显然是不行的。 因为这样做会得到[1,3,4,[3,4,5]]
我们只能用一个循环去一个一个的push(当然也可以用arr1.concat(arr2),但是concat方法并不改变arr1本身)
var arrLen=arr2.length
for(var i=0;i<arrLen;i++){
}
自从有了Apply,事情就变得如此简单
Array.prototype.push.apply(arr1,arr2)

本文介绍了JavaScript中apply方法的强大应用,包括实现类继承、数组操作优化及对象属性的动态扩展。通过示例展示了如何利用apply方法实现继承,以及如何在不修改原有对象的情况下扩展其属性和方法。
389

被折叠的 条评论
为什么被折叠?



