0

js中apply方法的使用

Posted by 晴云孤魂 on 2011 年 10 月 03 日 in About Javascript And more |

1、对象的继承,一般的做法是复制:Object.extend

prototype.js的实现方式是:

Object.extend = function(destination, source) {
for (property in source) {
destination[property] = source[property];
}
return destination;
}

除此之外,还有种方法,就是:Function.apply(当然使用Function.call也是可以的)

apply方法能劫持另外一个对象的方法,继承另外一个对象的属性

Function.apply(obj,args)方法能接收两个参数

obj:这个对象将代替Function类里this对象

args:这个是数组,它将作为参数传给Function(args–>arguments)

apply示范代码如下:

学生类本来不具备任何方法,但是在Person.apply(this,arguments)后,

他就具备了Person类的sayhello方法和所有属性。

在Print.apply(this,arguments)后就自动得到了show()方法

2、利用Apply的参数数组化来提高

Function.apply()在提升程序性能方面的技巧

我们先从Math.max()函数说起,Math.max后面可以接任意个参数,最后返回所有参数中的最大值。

比如
alert(Math.max(5,8)) //8
alert(Math.max(5,7,9,3,1,6)) //9

但是在很多情况下,我们需要找出数组中最大的元素。
var arr=[5,7,9,1]
alert(Math.max(arr)) // 这样却是不行的。一定要这样写

function getMax(arr){
var arrLen=arr.length;
for(var i=0,ret=arr[0];i

Copyright © 2011-2024 晴云孤魂's Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress