JavaScript一直让我惊讶,这是另一个例子。我只是遇到了一些代码,一开始我不理解。所以我对它进行了调试,得到了这样的发现:

alert('a'['toUpperCase']());  //alerts 'A'

现在,如果toUpperCase()被定义为string类型的成员,这肯定是显而易见的,但最初对我来说没有意义。

不管怎么说,

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?

我确信我对JavaScript函数的基本概念缺少一些认真的理解。请帮助我理解这一点。


当前回答

foo。Bar和foo[' Bar ']是相等的,所以你发布的代码是相同的

alert('a'.toUpperCase())

当使用foo[bar](注意没有引号)时,你不使用文字名称bar,而是使用变量bar包含的任何值。所以使用foo[]符号来代替foo。允许您使用动态属性名。


让我们来看看callMethod:

首先,它返回一个以obj为参数的函数。当函数执行时,它将调用该对象上的方法。因此,给定的方法只需要存在于obj本身或它的原型链上的某个地方。

在toUpperCase的情况下,该方法来自string .prototype.toUpperCase -为每个存在的字符串都有一个单独的方法副本是相当愚蠢的。

其他回答

anyObject['anyPropertyName']与anyObject相同。当anyPropertyName没有问题字符时。

参见MDN中的“使用对象”。

toUpperCase方法附加到类型String上。当你在一个基本值上调用一个函数时,这里'a',它会自动提升为一个对象,这里是String:

在要对基本字符串或对象调用方法的上下文中 属性查找时,JavaScript会自动换行字符串 元素,并调用该方法或执行属性查找。

你可以通过记录String.prototype.toUpperCase来看到这个函数的存在。

基本上javascript把所有东西都当作一个对象,或者说每个对象都可以被看作一个字典/关联数组。函数/方法的定义方式与对象完全相同——作为这个关联数组中的一个条目。

本质上,你是在引用/调用(注意'()')' a'对象的'toUpperCase'属性(在这里是字符串类型)。

以下是我脑海中的一些代码:

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

每个JavaScript对象都是一个哈希表,因此你可以通过指定一个键来访问它的成员。例如,如果一个变量是一个字符串,那么它应该有toUpperCase函数。你可以通过

var str = "a"
str['toUpperCase'](). // you get the method by its name as a key and invoke it.

通过inline str,你可以有下面

"a"["toUpperCase"]()

toUpperCase是一个标准的javascript方法:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase

它像'a'['toUpperCase']()一样工作的原因是toUpperCase函数是字符串对象'a'的属性。可以使用object[property]或object.property引用对象的属性。语法'a " toUpperCase'表示您正在引用'a'字符串对象的'toUpperCase'属性,然后调用它()。

foo。Bar和foo[' Bar ']是相等的,所以你发布的代码是相同的

alert('a'.toUpperCase())

当使用foo[bar](注意没有引号)时,你不使用文字名称bar,而是使用变量bar包含的任何值。所以使用foo[]符号来代替foo。允许您使用动态属性名。


让我们来看看callMethod:

首先,它返回一个以obj为参数的函数。当函数执行时,它将调用该对象上的方法。因此,给定的方法只需要存在于obj本身或它的原型链上的某个地方。

在toUpperCase的情况下,该方法来自string .prototype.toUpperCase -为每个存在的字符串都有一个单独的方法副本是相当愚蠢的。