js严格模式——arguments变为参数的静态副本

show u the code !

//一般模式
  ! function (a){
    arguments[0]=100;
    console.log(a);//undefined
  }();
  ! function (b){
    arguments[0]=100;
    console.log(b);//100
  }(1);
  ! function (c){
    //arguments[0]=100;
    console.log(c);//undefined
  }();
  ! function (d){
    //arguments[0]=100;
    console.log(d);//1
  }(1);

解释一下,

  ! function (b){
    arguments[0]=100;
    console.log(b);//100
  }(1);

在一般模式下,如果定义了一个函数,调用它并且传递参数,那么它对应的形参和arguments[0]有一个相互的绑定关系,就是说如果我们修改了arguments[0],那么这个函数对应的形参b就会被修改了,所以输出100。

如果我们现在不给函数传值,就是像下面这个样子,

! function (a){
    arguments[0]=100;
    console.log(a);//undefined
  }();

那么无论我们如何修改arguments[0]的值,输出的都是undefined,因为宝宝你没有传递参数进去啊,~ o( ̄▽ ̄)ブ

然而,在严格模式下,arguments[0]变为参数的静态副本,就是说无论函数的参数有没有传递,都不会和arguments相互影响,所以呢,我们看看下面代码。

//严格模式
  ! function (a){
    'use strict';
    arguments[0]=100;
    console.log(a);//undefined
  }();
  ! function (b){
    'use strict';
    arguments[0]=100;
    console.log(b);//1
  }(1);
  ! function (c){
    'use strict';
    //arguments[0]=100;
    console.log(c);//undefined
  }();
  ! function (d){
    'use strict';
    //arguments[0]=100;
    console.log(d);//1
  }(1);

需要注意的是,

! function (a){
    'use strict';
    arguments[0].x=100;
    console.log(a.x);//100
  }({x:1});

但是如果传入的是一个对象的话,将会按照共享传递,使用arguments修改对象的属性,那么还是会相互影响的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值