js call()的用法

js call()的用法

作者:LAMP小白  点击:1815  发布日期:2013-01-03 11:29:00  返回列表
简单的说,就是把obj1的方法放到obj2上面去运行
语法:
obj1.method1.call(obj2,argument1,argument2)

function haha() {
    this.name = 'haha name';
    this.showName = function(a) {
        console.log(this.name+a);
    }
}
function hehe() {
    this.name = 'hehe name';
}
var obj = new haha();
var obj2 = new hehe();
obj.showName.call(obj2, 'aaaaaaa');


结果是 mio_#39;hehe name aaaa..mio_#39;;

call还能实现多态继承

function Class10()
{
    this.showSub = function(a,b)
    {
        alert(a-b);
    }
}
function Class11()
{
    this.showAdd = function(a,b)
    {
        alert(a+b);
    }
}
function Class2()
{
    Class10.call(this);
    Class11.call(this);
}
var c2 = new Class2();
c2.showAdd(1,22);


上一篇:第一类对象 First-class object 下一篇:快递查询API
0