dan dan - 1 month ago 4
Javascript Question

How does this javascript object with parameters work?

I am working on someone else's code and I don't understand how this object works?

obj[fnName](param, param1)


I understand obj[fnName], but how can the object be passed values?

the full statment is
var res = obj[fnName](param, param1)
;

param and param1 can be an object or a string

If param or param1 is null then the statement is null

Answer

In JavaScript, functions are first class objects. You can treat them just like any other value. You can pass them around and you can assign them places, including to properties of other objects.

var obj = {};
obj.foo = 1; // A number
obj.bar = "bar"; // A string
obj.baz = function baz (arg1, arg2) { console.log(arg2, arg1); }; // A function
obj.baz(obj.foo, obj.bar);
Comments