[英]Javascript Function Parameter argument or global variable
var x=10;
function foo(){
x=120;
alert(arguments[0]); //outputs 10
}
foo(x);
如何知道函數中使用的x
是參數還是全局變量?
如果我提供了這個
function foo(x){
x=120;
console.log(arguments[0]);//logs 120
}
foo(x);
這兩個代碼之間有什么區別,幕后發生了什么以及參數數組如何變化?
var x=10; // this is variable of window namespace
function foo(x){
// It will make variable of this functions. Every function make its own namespace.
// So now you have x in local namespace, so you can't touch x from global
// namespace, becouse you gave them same names. With for example function foo(a),
// global x would be still accessible.
x=120;
// Here, you change value of x. Program will ask the deepest namespace if there
// is any x variable. If not, it will continue upper and upper. Right now,
// we have local x variable, so it will change value of local variable, which
// will extinct at the end of our function. The most upper namespace is global
// namespace. One more deeper is window namespace.
alert(arguments[0]);
// arguments is Array, which every function has as its property. Via arguments,
// you can touch every argument, that is passed to function. Later, I will
// show you an example
}
foo(12);
// finaly here, you call function foo and you set local x = 12. But then,
// you rewrite local x, so it is 120. After all, you alert first argument,
// which is local x, which is 120.
現在進行修改:
var x=10;
function foo(a){ // now we have different name for local variable
x=120; // so our x is x from window namespace
alert(arguments[0]); // now output is a, which will be 12
alert(x); // and x is 120
}
foo(12);
alert(x); // x will be still 120...
帶有論點的不同故事
var x=10;
function foo(){ // we didnt declare any local variable
x=120; // so our x is x from window namespace again
alert(arguments[0]);
// output is 12, becouse we can touch arguments via
// arguments array, even if we didnt declare any local variables
}
foo(12);
基本上,arguments函數的屬性允許我們做魔術。 它使代碼難以理解,但功能非常強大。 很少有使用它們的好主意。 明智地使用它們...
參數和局部變量指向內存中的同一位置。 因此,更改一個將立即更改另一個。
我怎么知道在函數內使用的xim是參數還是全局變量?
通過檢查函數的參數列表。 如果它提到這樣的參數x
:
function foo(x) {
那么您知道x
是一個參數。 它是arguments[0]
的別名(別名),因為它是第一個參數。 arguments
對象不是真正的數組。 它具有名稱為數字的屬性,並且具有length屬性,因此它看起來像一個數組,但是缺少數組的其他功能。
您可以將arguments
視為函數調用中傳遞的值的最終存儲。 參數名稱是獲取存儲在arguments
中的值的便捷方法。
如果您的職能開始:
function foo() {
那么它沒有參數。 您在函數內部引用的任何內容都必須是用另一種方式定義的值。 它可能是在函數內部聲明的局部變量:
function foo() {
var x = 10;
或者它可以引用函數外部聲明的名稱:
var x;
function foo() {
x = 10;
在沒有“嚴格模式”的JavaScript中,可以這樣說:
function foo() {
x = 10;
無需在任何地方聲明var x
。 結果是x將被創建為全局變量(或全局對象的屬性,例如在瀏覽器中將創建window.x
)。這是大量的bug,因為您可能會拼寫變量名而不會注意到您給一個不存在的變量賦值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.