JavaScript中的'a'['toUpperCase']()如何以及为什么工作? [英] How and why does 'a'['toUpperCase']() in JavaScript work?

查看:95
本文介绍了JavaScript中的'a'['toUpperCase']()如何以及为什么工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript让我感到惊讶,这是另一个例子。我刚刚遇到了一些我一开始就不明白的代码。所以我调试了一下,发现了这个结果:

  alert('a'['toUpperCase']()); //警告'A'

现在如果 toUpperCase() 被定义为字符串类型的成员,但最初没有意义。



无论如何,




  • 是否可以工作,因为 toUpperCase 是'a'的成员?或者幕后有其他事情发生?
  • code 我读过的函数如下:

      function callMethod(method){
    return function(obj){
    return obj [method](); // **我怎么能确定方法将永远是obj的成员**
    }
    }

    var caps2 = map(['a','b' ,'c'],callMethod('toUpperCase')); // ['A','B','C']
    //忽略map()函数的细节,它基本上调用数组中每个
    //元素的方法,并形成另一个结果数组并返回它

    ANY 方法上调用<强>任何对象。但是这是否意味着指定的方法已经是指定对象的隐式成员? 我错过了对JavaScript函数基本概念的认真理解。请帮我理解这一点。

    解决方案




    • .toUpperCase() String.prototype

    • 'a'是一个原始值,但被转换为其对象表示形式

    • 我们有两种可能的符号来访问对象属性/方法,点符号和括号表示法



    所以

     'a'['toUpperCase']; 

    是通过括号记号访问属性 toUpperCase ,来自 String.prototype 。由于此属性引用了方法,我们可以通过附加()

      '一个'[ 'toUpperCase'](); 


    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.

    解决方案

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

    这篇关于JavaScript中的'a'['toUpperCase']()如何以及为什么工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆