Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

令人头疼的 arguments #111

Closed
islishude opened this issue Sep 20, 2017 · 0 comments
Closed

令人头疼的 arguments #111

islishude opened this issue Sep 20, 2017 · 0 comments
Labels

Comments

@islishude
Copy link
Owner

islishude commented Sep 20, 2017

下面这一题来自 javascript-puzzlers

function sidEffecting(ary) {
  ary[0] = ary[2]
}
function bar(a,b,c) {
  c = 10
  sidEffecting(arguments)
  return a + b + c
}
bar(1,1,1)

上述的结果是什么?答案是21,当然这是非严格模式,如果严格模式,那么答案为12。

以我的理解简单非严格模式下,函数形参和arguments绑定,二者无论谁修改,都会互相影响。

但是,严格模式下,任何在函数体内的修改,或形参,或 arguments 只会影响自己,不会影响对方,可以修改下列代码试一试。

function test(a, b, c) {
    // 'use strict'
    var a = 4 
    console.log(a + b + c)
    // arguments[0] = 4
    console.log(arguments[0] + arguments[1] + arguments[2])
}

test(1,2,3)

严格模式下,参数的值不会随 arguments 对象的值的改变而变化。在正常模式下,对于第一个参数是 arg 的函数,对 arg 赋值时会同时赋值给 arguments[0],反之亦然(除非没有参数,或者 arguments[0] 被删除)。严格模式下,函数的 arguments 对象会保存函数被调用时的原始参数。arguments[i] 的值不会随与之相应的参数的值的改变而变化,同名参数的值也不会随与之相应的 arguments[i] 的值的改变而变化。

有意思的是在ES6下,如果使用函数默认值,也会出现类似严格模式的效果。

function test(a, b, c = 3) {
    var a = 4 
    console.log(a + b + c)
    // arguments[0] = 4
    console.log(arguments[0] + arguments[1] + arguments[2])
}

test(1,2,3)

花了半个小时,发现自己以前对严格模式理解还有不足,以后这道题作为面试题还不错。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant