call、apply、bind的用法

在网上看到的一句话概括,感觉很明了,记录一下
A.functionA.apply(B,[arg1,arg2,...])
=== A.functionA.call(B,arg1,arg2,...)
=== A.functionA.bind(B,arg1,arg2,...)()
===B.functionA(arg1,arg2,...)

也就是自己没有的属性和方法,去借用别人的方法和属性来执行操作。

一些demo

function Animate(name){
        this.name = name;
        this.sayName = function(){
            console.log(this.name);
        }
    }

    function Cat(name){
        Animate.apply(this,[name]);
        //等价于
        //Animate.call(this,name);
        //bind 传参与call一样,只是后面需要加个调用
        //Animate.bind(this,name)();
    }

    var cat = new Cat('miaomiao');
    cat.sayName(); //miaomiao
var arr1 = new Array(1,4,15,9,12,8);
var max = Math.max.apply(Math,arr1);
console.log(max); // 15

你可能感兴趣的:(call、apply、bind的用法)