简体   繁体   English

javascript中的函数参数-local或global

[英]function parameters in javascript -local or global

I am a new learner, learning to code front end development. 我是一名新手,正在学习编码前端开发。 I want to know about the global and local variables in JavaScript functions. 我想了解JavaScript函数中的全局变量和局部变量。 I understand the local and global, but how about the function parameters, are they local or global? 我了解局部和全局,但是函数参数是局部还是全局呢?

Should I always define a function as function add(a,b) or function add(var a, var b) ? 我应该始终将函数定义为function add(a,b)还是function add(var a, var b)吗?

Somewhere I read that any variables defined without the var keyword inside a function becomes global. 我在某处看到,在函数内部没有var关键字的情况下定义的所有变量都将变为全局变量。 This point is confusing me. 这一点使我感到困惑。

The first one. 第一个。 function add(a,b)

Using the var keyword up there is actually a syntax error. 实际上,使用var关键字存在语法错误。

somewhere I read that any variables defined without the var keyword inside a function becomes global 我读到某个地方,在函数内部没有var关键字的情况下定义的任何变量都变为全局变量

That's true, but only when you do c = 'something' . 没错,但只有在您执行c = 'something'时才可以。 Function parameters are always locally scoped. 函数参数始终在本地范围内。

The parameters are local to the function, but this is only half the truth, since objects are passed by reference. 参数是函数的局部参数,但这仅是事实的一半,因为对象是通过引用传递的。 So if your function takes an object and modifies any member of this object, then the change is also seen outside of the function (because it's the same object). 因此,如果您的函数接受一个对象并修改了该对象的任何成员,则更改也将在函数外部看到(因为它是同一对象)。

Try the following in a node shell to demonstrate: 在节点外壳中尝试以下操作以进行演示:

var obj = { a:0 };
obj;
function f(o) { o.a++; }
f(obj);
obj;

$ node $节点

var obj = { a:0 }; var obj = {a:0};

undefined 未定义

obj; obj;

{ a: 0 } {a:0}

function f(o) { o.a++}; 函数f(o){o.a ++};

undefined 未定义

f(obj); f(obj);

undefined 未定义

obj; obj;

{ a: 1 } {a:1}

In function add(a,b) a and b are only accessible within the function so they are local to that function. function add(a,b) a和b仅可在函数内访问,因此它们在该函数中是本地的。

function add(var a, var b) is incorrect syntax. function add(var a, var b)的语法不正确。 You can't put var there. 你不能把var放在那里。

You must declare a function such as function add(a, b). 您必须声明一个函数,例如函数add(a,b)。 a and b are the parameters you'll give to the function when you will call it. a和b是调用该函数时将赋予该函数的参数。

They don't exist at the moment of declaration, and are local to the variable. 它们在声明时不存在,并且是变量的局部变量。 They are more or less a reference to the variables you'll pass to your function when calling it. 它们或多或少是您在调用函数时将传递给函数的变量的引用。

 var num1 = 4; var num2 = 3; function add(a, b){ return a + b; } var result = add(num1, num2); // result : 7 

Variables declared inside a bracket's function without the keyword var become global, such as result in the following example : 在方括号的函数内声明而没有关键字var的变量变为全局变量,例如以下示例中的result:

 function add(a, b){ result = a + b ; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM