How and why does 'a'['toUpperCase']() in JavaScript work?
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,
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.
To break it down.
.toUpperCase()
is a method of String.prototype
'a'
is a primitive value, but gets converted into its Object representation So
'a'['toUpperCase'];
is the access via bracket notation on the property toUpperCase
, from String.prototype
. Since this property references a method, we can invoke it by attaching ()
'a'['toUpperCase']();
foo.bar
and foo['bar']
are equal so the code you posted is the same as
alert('a'.toUpperCase())
When using foo[bar]
(note tha lack of quotes) you do not use the literal name bar
but whatever value the variable bar
contains. So using the foo[]
notation instead of foo.
allows you to use a dynamic property name.
Let's have a look at callMethod
:
First of all, it returns a function that takes obj
as its argument. When that function is executed it will call method
on that object. So the given method just needs to exist either on obj
itself or somewhere on its prototype chain.
In case of toUpperCase
that method comes from String.prototype.toUpperCase
- it would be rather stupid to have a separate copy of the method for every single string that exists.
You can either access the members of any object with .propertyName
notation or ["propertyName"]
notation. That is the feature of JavaScript language. To be sure that member is in the object, simply check, if it is defined:
function callMethod(method) {
return function (obj) {
if (typeof(obj[method]) == 'function') //in that case, check if it is a function
return obj[method](); //and then invoke it
}
}
链接地址: http://www.djcxy.com/p/2876.html
上一篇: 修改函数或从字符串评估函数