JS中call()方法

// arguments变量的写法

function sortNumbers(){
    return Array.prototype.slice.call(argarguments).sort();
    //call 改变this的指向
}

// obj1.(method).call(obj2,arg1,arg2)
// call的作用就是把obj1的方法放到obj2上使用,后面arg1...这些作为obj1的参数传入


function add(x,y){
    console.log(x+y);
}
function minus(x,y){
    console.log(x-y)
}
add.call(minus,10,6);//16

function myFun1(){
    this.name = 'xiaolei';
    this.myTxt = function(txt){
        console.log('I am',txt);
    }
}
function myFun2(){
    myFun1.call(this);
}
var myFun3 = new myFun2();
myFun3.myTxt('handan');//I am handan
console.log(myFun3.name);//xiaolei

评论

暂无评论