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函数的基本概念缺少一些认真的理解。请帮助我理解这一点。


当前回答

在Javascript中,对象就是对象。这就是它们的性质{}。对象属性可以使用以下任意一种来设置:a.greeting = 'hello';或者a['greeting'] = 'hello';。两种方法都有效。

检索的工作原理相同。a.greeting(不带引号)是'hello', a['greeting']是'hello'。例外:如果属性是一个数字,则只有括号方法有效。点方法没有。

a是一个带有toUpperCase属性的对象它实际上是一个函数。您可以检索该函数并随后以'a'.toUpperCase()或'a'['toUpperCase']()两种方式调用它。

但在我看来,更好的方法来写地图函数将是 Var caps = ['a','b','c']。map(函数(char){返回char. touppercase ();}) 那么谁需要callMethod函数呢?

其他回答

您可以使用.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
    }
}

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

alert('a'.toUpperCase())

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


让我们来看看callMethod:

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

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

javascript中几乎所有的东西都可以被当作对象。在你的例子中,字母本身充当一个字符串对象,toUpperCase可以作为它的方法被调用。方括号只是访问对象属性的另一种方式,由于toUpperCase是一个方法,因此需要在['toUpperCase']旁边使用simple括号(),形成['toUpperCase']()。

'a'['toUpperCase']()相当于'a'.toUpperCase()

'a'['toUpperCase']() // returns A
'a'.toUpperCase() // returns A

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'属性,然后调用它()。

如果你问它是怎么工作的我就是这么读的。这是一个简单的数学函数。要理解它,您需要查看ascii表。给每个字母赋一个数值。要隐藏它,竞争对手只需使用一个逻辑语句来隐藏,例如 If(ChcrValue > 80 && charValue < 106) //小写字母集合 那么charValue = charValue - 38;//下集和上集之间的距离

就是这么简单,我实际上并没有费心去查找正确的值,但这基本上是将所有小写字母转换为大写值。