Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

对于默认传参值的疑惑

image.png
这是《你不知道的js 里面的一个解释》,没太懂;
为什么z 是一个没初始的参数变量而 w 确实?z 和 w 有啥区别,难道不一样?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

函数形参等同于函数内声明的局部变量,其作用域只在函数内。上面代码等价于:

var w = 1, z = 2;

function foo() {
  var x = arguments[0] !== undefined ? arguments[0] : w + 1;
  var y = arguments[1] !== undefined ? arguments[1] : x + 1;
  var z = arguments[2] !== undefined ? arguments[2] : z + 1;

  console.log(x, y, z);
}

在函数foo内访问的z是函数内声明的局部变量。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...