this.String = { Get : function (val) { return function() { return val; } } };
What is the ‘:’ doing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Others have already explained what this code does. It creates an object (called
this.String) that contains a single function (calledGet). I’d like to explain when you could use this function.This function can be useful in cases where you need a higher order function (that is a function that expects another function as its argument).
Say you have a function that does something to each element of an
Array, lets call itmap. You could use this function like so:What the
mapfunction will do, is create a new array containing the values[2, 3, 4]. It will do this by calling the functionincwith each element of the array.Now, if you use this method a lot, you might continuously be calling
mapwith all sorts of arguments:If for some reason you’d want to replace the entire array with the same string (but keeping the array of the same size), you could call it like so:
This will create a new array of the same size as
arr, but just containing the string'my String'over and over again.Note that in some languages, this function is predefined and called
constorconstant(since it will always return the same value, each time you call it, no matter what its arguments are).Now, if you think that this example isn’t very useful, I would agree with you. But there are cases, when programming with higher order functions, when this technique is used.
For example, it can be useful if you have a tree you want to ‘clear’ of its values but keep the structure of the tree. You could do
tree.map(this.String.Get('default value'))and get a whole new tree is created that has the exact same shape as the original, but none of its values.