Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is function with brackets mean?

Tags:

javascript

Does anyone know what is test[name] mean?

function test(value){
  copy(value||{},this);
}
test[name] = function(){
    return "test"
}
like image 630
user1598686 Avatar asked Sep 24 '26 19:09

user1598686


2 Answers

This will be easiest to explain with an example:

var name = "foo";
test[name] = function(){
    return "test"
};

This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.

You could call this function using any of the following methods:

  • test[name]()
  • test["foo"]()
  • test.foo()

Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.

like image 72
Andrew Clark Avatar answered Sep 27 '26 08:09

Andrew Clark


Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.

test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.

This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.

like image 29
Nick Tomlin Avatar answered Sep 27 '26 09:09

Nick Tomlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!