Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and why does 'a'['toUpperCase']() in JavaScript work?

To break it down.

  • .toUpperCase() is a method of String.prototype
  • 'a' is a primitive value, but gets converted into its Object representation
  • We have two possible notations to access object properties/methods, dot and bracket notation

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
    }
}

Basically javascript treats everything as an Object, or rather every object can be viewed as a dictionary/associative-array. And functions/methods are defined the exact same way for the object - as an entry in this associative array.

So essentially, you're referencing/calling (notice the '()' ) the 'toUpperCase' property, of the 'a' object (which is a string type, in this case).

Here's some code of the top of my head:

function myObject(){
    this.msg = "hey there! ;-)";
    this.woop = function(){
        alert(this.msg); //do whatever with member data
    }
}

var obj = new myObject();
alert( obj.msg );
alert( obj['msg'] );
obj['woop']();