Javascript: undefined as a function parameter

此生再无相见时 提交于 2019-12-19 19:46:10

问题


On this page, it shows some example code, containing the following line:

var Subject = ( function( window, undefined ) {

What is the undefined as a function parameter?


回答1:


This is used to prevent from overriding the value of undefined in non-strict mode.

In non-strict mode, the value of undefined can be override by assigning other value to it.

undefined = true; // Or any other value

So, using the value of undefined will not work as expected.

In strict-mode, undefined is read-only and assigning value to it will throw error.

In the code, the value to the last parameter is not passed, so it'll be implicitly passed as undefined.

var Subject = ( function( window, undefined ) {

}(window)); // <-- No parameter is passed for the last value



回答2:


That is done to make sure that undefined always is undefined. In JavaScript, since undefined isn't a reserved word but a regular variable, this would be allowed for instance:

 undefined = 2; // Assign a different value to undefined
 if (undefined == 2)  // Now this statement would be true

So in your case

var Subject = ( function( window, undefined ) {

They pass in window and use it , but then they don't pass a second value to the undefined parameter, thus undefined will be undefined.




回答3:


Because you used to be able to redefine the value of undefined, but not anymore. Undefined is a special type that has several use cases. If it was redefined to true, code like this would break:

if(my_var === undefined) { 
     dont_load_missiles());
} else {
     load_missiles();
}



回答4:


I recently asked a similar question ( SO link ) and the community suggested this article.

Following statements in the selected answer ( link ) theoretically answers the question;

  • This is used to prevent from overriding the value of undefined in non-strict mode.
  • In non-strict mode, the value of undefined can be override by assigning other value to it.

I believe a practical example might be helpful

var undefined = 7;
function printUndefined(undefined) {
  document.getElementById("output").innerHTML += undefined + "<br/>";
}

printUndefined(); // Output is undefined
printUndefined(undefined); // Output is 7
printUndefined(10); // Output is 10

JSfiddle

Therefore the only guarantee is that the method caller is in control of the context.



来源:https://stackoverflow.com/questions/33383647/javascript-undefined-as-a-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!