js中call与apply的区别以及使用~

今天看了一下call与apply的区别~~

<!DOCTYPE html>
<html>
<head>
    <title>testCall</title>
</head>
<body>

</body>
<script type="text/javascript">
    /*
        apply,call 都是为了改变上下文this的指向
        两者的区别:
        Function.apply(thisobj,[arg1,arg2....])
        Function.call(thisobj,arg1,arg2....)

        thisobj:这个对象将代替Function类里this对象
        arg1,arg2....:这个是数组或类数组,apply方法把这个集合中的元素作为参数传递给被调用的函数

        非严格模式下,当我们第一个参数传递为null或undefined时,函数体内的this会指向默认的宿主对象,在浏览器中则是window
     */
    
    function test () {
        console.log(this == window)
    }
    test.call(null);   //true
    test.apply(null); //true

    /* 用法1:使用别人的方法 */
    var foo = {
        name: "ming",
        logName:function() {
            console.log(this.name)
        }
    }
    var bar={
      name:"xiaowang"
    };

    foo.logName.call(bar)

    /* 实现继承 */
    function Animal(name) {
        this.name = name;
        this.showName = function() {
            console.log(this.name)
        }
    }

    function Cat(name) {
        Animal.call(this,name)
        //this将替代Animal的this的指向
    }
    var cat = new Cat("paopao")
    cat.showName();

    function(){
      Array.prototype.push.call(arguments,4);
      console.log(arguments);//[1, 2, 3, 4]
    })(1,2,3)

    /* 数组合并 */
    var arr1=new Array("1","2","3");
    var arr2=new Array("4","5","6");
    Array.prototype.push.apply(arr1,arr2);  //相当于arr1调用了push方法,将arr2
    console.log(arr1);//["1", "2", "3", "4", "5", "6"]

    

</script>
</html>

 

转载于:https://www.cnblogs.com/Mrs-pao/p/7993646.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值