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.
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();
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]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.