[英]Are all parameters to Javascript functions passed only by value?
If I have a variable like this: 如果我有这样的变量:
I created something similar to an ENUM like this: 我创建了类似于ENUM的内容,如下所示:
var ContentStatusId = {
All: 0,
Production: 1,
Review: 2,
Draft: 3,
Concept: 4
}
When I call a function like this: 当我调用这样的函数时:
doTask(myParam) {
var a =
}
With doTask(ContentStatusId.All); 使用doTask(ContentStatusId.All);
Is there any way that I can find out anything about the parameter passed to the function or is it completely passed by value only? 我有什么办法可以找到有关传递给函数的参数的任何信息,还是仅按值完全传递? Are there any other ways to pass parameters to a function?
还有其他方法可以将参数传递给函数吗?
In JavaScript all parameters are passed by value. 在JavaScript中, 所有参数均按值传递。
In the case of a primitive, the value is the primitive value. 对于基本类型,该值为原始值。
function test(arg) {
console.log(arg);
}
test(1);
arg
will have the value of 1. arg
的值为1。
However, if you say 但是,如果你说
test({});
then arg
will contain a value which is a REFERENCE to the object we just created. 那么
arg
将包含一个值,该值是对我们刚创建的对象的引用。
Edit to address comment 编辑以发表评论
You can do... 你可以做...
doTask(myParam) {
if (myParam === ContentStatusId.Review) {
// Do stuff
}
}
doTask(ContentStatusId.Review);
or 要么
doTask(myParam) {
switch(myParam) {
case ContentStatusId.Review:
// Do stuff
break;
}
}
There is nothing calling pass by reference in javascript. 在javascript中没有通过引用调用传递。
Everything gets passed by value only . 一切仅通过价值传递。
Eg 例如
If in case of primitive value 如果是原始值
eg 例如
var a = 10;
console.log(a); // 10
fun xyz(a); // passing a
function xyz(a) {
a += 10;
console.log(a); // 20
} // function will receive the value. If you modify it, It will still will not be reflected back to what you passed
console.log(a); // 10
Other way round, 另一边,
When you pass object to a function, The references gets copied. 将对象传递给函数时,引用将被复制。
eg 例如
var obj = { 'a': 10 };
console.log(obj.a); // 10
function xyz(obj) {
obj.a = obj.a + 10;
console.log(obj.a); // 20
} // here the obj will be copied as reference. So when you modify it, It will get reflected back to original object.
console.log(obj.a); // 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.