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
367 views
in Technique[技术] by (71.8m points)

javascript - JavaScript中'a'['toUpperCase']()的工作方式和原因是什么?(How and why does 'a'['toUpperCase']() in JavaScript work?)

JavaScript keeps surprising me and this is another instance.(JavaScript让我感到惊讶,这是另一个例子。)

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.(现在,如果将toUpperCase()定义为字符串类型的成员,这一点必须明显,但最初对我来说没有意义。) Anyway,(无论如何,) does this work because toUpperCase is a member of 'a'?(这是否有效,因为toUpperCase是'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.(它是在ANY对象上调用ANY方法的通用函数。) 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.(我确信我对JavaScript函数的基本概念缺乏认真的理解。) Please help me to understand this.(请帮我理解这个。)   ask by Mahesha999 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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(.toUpperCase()String.prototype一种方法) 'a' is a primitive value, but gets converted into its Object representation('a'是原始值,但会转换为其Object表示形式) 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 .(是来自String.prototype的属性toUpperCase上的括号表示法访问。) 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

...