Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

function - 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,

  • 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...