开发者

I want to pass JavaScript Objects as Arguments

开发者 https://www.devze.com 2023-01-31 21:06 出处:网络
function foo(o){ o=o || {}; } foo(one:1); // ??? alert(foo(one); 开发者_运维技巧// ??? foo(one:1,two:2,three:3) // ???
function foo(o){
    o=o || {};
}

foo(one:1); // ???
    alert(foo(one); 开发者_运维技巧// ???


foo(one:1,two:2,three:3) // ???
    alert(foo(one,two,three)); // ???

What exactly does this piece of JavaScript do?

o = o || {};

I've seen in many codes.


The expression

o = o || {};

means

Interpret the value of the variable "o" as a boolean. If that value is "true", then set "o" to its current value. If "false", set "o" to refer to a new Object instance.

The point is to make sure that "o" is not null, and to initialize it to a new Object instance if it is.

As far as calling the function, you need to use the "object literal" notation:

foo({ key1: value, key2: value, ... });

edit — as noted in a comment, the interpretation of the value of "o" as boolean is a rather interesting subject of its own. In this particular case, the intent is to check to see whether "o" is null. There are values for "o" that evaluate to false but which might need to be treated differently here, but there's obviously not enough context in the question to know.


you would create your object

var arg = {key: val};

and then

var result = foo(arg);

you pass the object that is the argument into the function. If your function can take more than one arg, when you define the function you would

   var theFunction = function(arg1, arg2, arg3) {
        // arg1, arg2, and arg3 are all references in this function
   }

that way arg1, arg2, and arg3 are defined to be arguments. Javascript has some flexibility in that you could pass as many arguments as you want in; it is good design to define the function with explicit arguments so the API is clear. However, there are cases where you just don't know, so in Javascript you can get all the arguments that were passed in with the 'arguments' variable. Javascript makes this variable available in all functions. But you should use it rarely. Here is a link with examples

http://www.seifi.org/javascript/javascript-arguments.html

the

 o = o || {};

sets the variable 'o' to be o, or if o is not defined, an empty object literal. It basically initializes the variable if it is 'falsy'. It is a technique to prevent null object issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消