JavaScript keeps surprising me and this is another instance. I just came across some code which I did not understood at first. So I debugged it and came to this finding:
alert('a'['toUpperCase']()); //alerts 'A'
Now this must be obvious if toUpperCase()
is defined as a member of string type, but it did not make sense to me initially.
Anyway,
- does this work because
toUpperCase
is a member of 'a'? Or there is something else going on behind the scenes?
the code I was reading has a function as follows:
function callMethod(method) {
return function (obj) {
return obj[method](); //**how can I be sure method will always be a member of obj**
}
}
var caps2 = map(['a', 'b', 'c'], callMethod('toUpperCase')); // ['A','B','C']
// ignoring details of map() function which essentially calls methods on every
// element of the array and forms another array of result and returns it
It is kinda generic function to call ANY methods on ANY object. But does that mean the specified method will already be an implicit member of the specified object?
I am sure that I am missing some serious understanding of basic concept of JavaScript functions. Please help me to understand this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…