1

Exactly what kind of Javascript function is this, and how exactly do I use it?

position = this[this.options.position](); 

I've looked up .call(), but there's hardly anything related to this strange use of Javascript.

Thank you.

2
  • This has nothing to do with call. What exactly do you not understand about this function call? This is just a property access yielding a function that is being called. Commented Sep 18, 2017 at 17:42
  • 2
    if this.options.position was 'left' then it's position = this.left(); Commented Sep 18, 2017 at 17:43

2 Answers 2

3

It's not a function, it's a function call. That expression looks up the property named by this.options.position on the object referenced by this and then calls the function that property's value refers to. So for instance, if this.options.position contains the string "one", then it's like doing position = this.one().

Example:

var obj = { options: {}, one: function() { console.log("This is function one"); return 1; }, two: function() { console.log("This is function two"); return 2; }, example: function() { var position = this[this.options.position](); console.log(position); } } obj.options.position = "one"; obj.example(); obj.options.position = "two"; obj.example();

Sign up to request clarification or add additional context in comments.

Comments

0

This has nothing to do with functions, but with property access. This one is called bracket notation. It allows you to access a property whose name is determined at runtime.

For example, these two are equivalent:

this.left() // dot notation // var position = 'left'; this[position](); // bracket notation 

If you have worked with arrays, then you have come across bracket notation already:

var arr = [1,2,3]; console.log(arr[0]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.