JavaScript 中的 'a'['toUpperCase']() 如何以及为什么工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15659809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How and why does 'a'['toUpperCase']() in JavaScript work?
提问by Mahesha999
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:
JavaScript 一直让我感到惊讶,这是另一个例子。我刚刚遇到了一些我一开始不理解的代码。所以我调试了它并得出了这个发现:
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'? Or there is something else going on behind the scenes? the codeI 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 ANYmethods on ANYobject. But does that mean the specified method will already be an implicit member of the specified object?
- 这是否有效,因为它
toUpperCase
是“a”的成员?还是幕后有其他事情发生? 我正在阅读的代码具有如下功能:
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
在任何对象上调用任何方法是一种通用函数。但这是否意味着指定的方法已经是指定对象的隐式成员?
I am sure that I am missing some serious understanding of basic concept of JavaScript functions. Please help me to understand this.
我确信我对 JavaScript 函数的基本概念缺少一些认真的理解。请帮助我理解这一点。
回答by jAndy
To break it down.
把它分解。
.toUpperCase()
is a method ofString.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
.toUpperCase()
是一种方法String.prototype
'a'
是一个原始值,但被转换为它的对象表示- 我们有两种可能的符号来访问对象属性/方法,点和括号符号
So
所以
'a'['toUpperCase'];
is the access via bracket notationon the property toUpperCase
, from String.prototype
. Since this property references a method, we can invoke it by attaching ()
是通过对属性的括号表示法的访问toUpperCase
,来自String.prototype
。由于此属性引用了一个方法,我们可以通过附加()
'a'['toUpperCase']();
回答by ThiefMaster
foo.bar
and foo['bar']
are equal so the code you posted is the same as
foo.bar
并且foo['bar']
相等所以您发布的代码与
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.
使用foo[bar]
(注意缺少引号)时,您不使用文字名称,bar
而是使用变量bar
包含的任何值。因此,使用foo[]
符号代替foo.
允许您使用动态属性名称。
Let's have a look at callMethod
:
让我们来看看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.
首先,它返回一个将obj
其作为参数的函数。执行该函数时,它将调用method
该对象。所以给定的方法只需要存在于其obj
自身或其原型链上的某处。
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.
如果toUpperCase
该方法来自String.prototype.toUpperCase
- 为每个存在的字符串单独复制该方法将是相当愚蠢的。
回答by Artyom Neustroev
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:
您可以使用.propertyName
符号或["propertyName"]
符号访问任何对象的成员。这就是 JavaScript 语言的特性。要确保该成员在对象中,只需检查它是否已定义:
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
}
}
回答by Nisk
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.
基本上,javascript 将所有内容都视为对象,或者更确切地说,每个对象都可以视为字典/关联数组。并且函数/方法以完全相同的方式为对象定义 - 作为此关联数组中的条目。
So essentially, you're referencing/calling (notice the '()' ) the 'toUpperCase' property, of the 'a' object (which is a string type, in this case).
所以本质上,您正在引用/调用(注意 ' ()' )'a' 对象(在本例中为字符串类型)的 'toUpperCase' 属性。
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']();
回答by Denys Séguret
anyObject['anyPropertyName']
is the same as anyObject.anyPropertyName
when anyPropertyName
hasn't problematic characters.
anyObject['anyPropertyName']
与没有问题的字符anyObject.anyPropertyName
时相同anyPropertyName
。
See Working with Objects, from the MDN.
请参阅来自 MDN 的使用对象。
The toUpperCase
method is attached to the type String. When you call a function on a primitive value, here 'a'
, it is automatically promoted to an object, here a String:
该toUpperCase
方法附加到类型字符串。当您在原始值上调用函数时,此处'a'
,它会自动提升为对象,此处为String:
In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.
在要在原始字符串上调用方法或发生属性查找的上下文中,JavaScript 将自动包装字符串原始并调用方法或执行属性查找。
You can see the function exists by logging String.prototype.toUpperCase
.
您可以通过 logging 看到该函数是否存在String.prototype.toUpperCase
。
回答by Yaw Boakye
So in Javascript, objects
are objects
. That is they're of this nature {}
. Object properties can be set using either of these: a.greeting = 'hello';
or a['greeting'] = 'hello';
. Both ways work.
所以在 Javascript 中,objects
是objects
. 那就是他们具有这种性质{}
。可以使用以下任一方法设置对象属性:a.greeting = 'hello';
或a['greeting'] = 'hello';
。两种方式都有效。
Retrieval works the same. a.greeting
(without quotes) is 'hello'
, a['greeting']
is 'hello'
. Exception: if the property is a number, only the bracket method works. The dot method doesn't.
检索工作相同。a.greeting
(不带引号)是'hello'
,a['greeting']
是'hello'
。例外:如果属性是数字,则只有括号方法有效。点方法没有。
So 'a'
is an object with 'toUpperCase'
property which is actually a function. You can retrieve the function and call it subsequently either way: 'a'.toUpperCase()
or 'a'['toUpperCase']()
.
'a'
具有'toUpperCase'
属性的对象也是如此,它实际上是一个函数。您可以检索该函数并随后通过以下任一方式调用它:'a'.toUpperCase()
或'a'['toUpperCase']()
。
But imo the better way to write the map function would be asvar caps = ['a','b','c'].map( function(char) { return char.toUpperCase(); } )
Who needs the callMethod
function then?
但是 imo 编写 map 函数的更好方法是var caps = ['a','b','c'].map( function(char) { return char.toUpperCase(); } )
谁需要这个callMethod
函数呢?
回答by Shuping
Every JavaScript object is a hash table thus you can access its members by specifying a key. for example, if a variable is a string, then it should has the toUpperCase function. So, you could invoke it by
每个 JavaScript 对象都是一个哈希表,因此您可以通过指定键来访问其成员。例如,如果一个变量是一个字符串,那么它应该有 toUpperCase 函数。所以,你可以通过调用它
var str = "a"
str['toUpperCase'](). // you get the method by its name as a key and invoke it.
so, by inline str, you could have below
所以,通过内联str,你可以在下面
"a"["toUpperCase"]()
回答by SteveP
toUpperCase is a standard javascript method: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase
toUpperCase 是一种标准的 javascript 方法:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase
The reason it works like 'a'['toUpperCase']()
is that the toUpperCase function is a property of the string object 'a'
. You can reference the properties on an object using object[property]
or object.property
. The syntax 'a''toUpperCase' indicates you are referencing the 'toUppercase' propert of the 'a' string object, and then calling it ().
它工作的原因'a'['toUpperCase']()
是 toUpperCase 函数是字符串对象的一个属性'a'
。您可以使用object[property]
或引用对象上的属性object.property
。语法 'a''toUpperCase' 表示您正在引用 'a' 字符串对象的 'toUppercase' 属性,然后调用它 ()。
回答by LarsH
But does that mean the specified method will already be an implicit member of the specified object?
但这是否意味着指定的方法已经是指定对象的隐式成员?
No. Someone could pass in an object that
不。有人可以传入一个对象
- does not have a property named
toUpperCase
; or - has a property named
toUpperCase
that is not a function
- 没有名为 的属性
toUpperCase
;或者 - 有一个名称
toUpperCase
不是函数的属性
In the first case, an error will be thrown because accessing a property that doesn't exist returns undefined
, and we can't invoke undefined
as a function.
在第一种情况下,会抛出错误,因为访问不存在的属性会返回undefined
,并且我们不能undefined
作为函数调用。
In the second case, an error will be thrown because again, we can't invoke a non-function as a function.
在第二种情况下,将抛出错误,因为我们不能再将非函数作为函数调用。
Remember that JavaScript is a very loosely-typed language. Little or no type checking occurs unless and until it has to. The code you showed works in certain cases because, in those cases, the passed object has a property named toUpperCase
, that is a function.
请记住,JavaScript 是一种非常松散类型的语言。除非必要,否则很少或不进行类型检查。您展示的代码在某些情况下有效,因为在这些情况下,传递的对象具有名为 的属性toUpperCase
,即一个函数。
The fact that the obj
argument isn't guaranteed to have the right types of properties doesn't bother JavaScript at all, so to speak. It adopts a "wait and see" attitude, and doesn't throw an error until an actual problem occurs at run time.
可以这么说,obj
不能保证参数具有正确类型的属性这一事实根本不会困扰 JavaScript。它采取“观望”的态度,直到运行时出现实际问题才抛出错误。
回答by Sanjay
Almost everything in javascript can be treated as an object. In your case the alphabet itself acts as a string object and toUpperCase
can be invoked as its method. The square brackets are just alternative way of accessing object properties and since toUpperCase
is a method hence the simplebracket ()
is needed next to ['toUpperCase']
forming ['toUpperCase']()
.
javascript 中的几乎所有东西都可以被视为一个对象。在您的情况下,字母表本身充当字符串对象,toUpperCase
可以作为其方法调用。方括号只是访问对象属性的替代方式,因为它toUpperCase
是一种方法,因此在形成()
旁边需要simplebracket 。['toUpperCase']
['toUpperCase']()
'a'['toUpperCase']()
is equivalent to 'a'.toUpperCase()
'a'['toUpperCase']()
相当于 'a'.toUpperCase()
'a'['toUpperCase']() // returns A
'a'.toUpperCase() // returns A