1. 程式人生 > >js嚴格模式——arguments變為引數的靜態副本

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修改物件的屬性,那麼還是會相互影響的