首页 > 语言 > JavaScript > 正文

js中apply方法的使用详细解析

2024-05-06 14:34:20
字体:
来源:转载
供稿:网友

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示范代码如下:
代码如下:
<script>
function Person(name,age){   //定义一个类,人类 
    this.name=name;     //名字 
    this.age=age;       //年龄
    this.sayhello=function(){alert("hello")};
}
function Print(){            //显示类的属性
    this.funcName="Print";
    this.show=function(){     
        var msg=[];
        for(var key in this){
            if(typeof(this[key])!="function"){
                msg.push([key,":",this[key]].join(""));
            }
        }
        alert(msg.join(" "));
    };
}
function Student(name,age,grade,school){    //学生类
    Person.apply(this,arguments);
    Print.apply(this,arguments);
    this.grade=grade;                //年级
    this.school=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后面可以接任意个参数,最后返回所有参数中的最大值。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选