【问题标题】:Javascript object with function and this带有函数和 this 的 Javascript 对象
【发布时间】:2018-05-29 11:57:27
【问题描述】:

我正在学习 JavaScript 对象。 我在下面构建了一些编码。当我删除 this.recall=recall 时,它不起作用。但是当我添加 this.recall=recall 时,整个代码都起作用了。我不知道为什么我需要把 this.recall=recall 来得到结果,因为它在函数被调用时没有任何价值。

<head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">
      function recall (){
        document.write('the height is:'+ this.height+'<br>');
        document.write('the weight is:'+ this.weight+'<br>');
        document.write('the age is:'+ this.age+'<br>');
      }
      function Private(height,weight,age){
        this.height=height;
        this.weight=weight;
        this.age=age;
        this.recall=recall;
      }
    </script>
  </head>
  <body>
    <script type="text/javascript">
      var man= new Private('170cm','60kg','26-year-old');
      man.recall();
    </script>
  </body>

【问题讨论】:

    标签: javascript function object this


    【解决方案1】:

    这是你的类的构造函数:

          function Private(height,weight,age){
            this.height=height;
            this.weight=weight;
            this.age=age;
            this.recall=recall;
          }
    

    您使用此语句向类添加方法:

    this.recall=recall;
    

    所以你可以在初始化类的对象后调用该函数:

    var man= new Private('170cm','60kg','26-year-old');
    

    【讨论】:

      【解决方案2】:

      为了调用一个函数,它必须在调用者的上下文中。 在这里,新的 Private 对象在引用变量 man 中返回。现在我们可以说人是一个对象。如果 man 对象没有调用方法,则无法调用它。 因此,当从 Private 函数返回时,如果调用函数是对象的一部分,它就可以工作。

      【讨论】:

      • 感谢您的回复。我想快速询问代码“this.recall=recall”在函数 Private 中的作用。因为自从我删除它以来它有一些作用,它没有工作。
      • 你应该阅读 javascript 中的新对象。当我们使用 new 运算符调用函数时,它会创建一个新对象。我们使用 this.sth = sth 评估的一切。作为该对象的属性。
      • 新对象被 man 变量引用。所以在调用函数内部,this 指的是 man,因为 man 调用了它。
      • 谢谢罗恩,我有点明白了。我将阅读 Javascript 中的 New。
      【解决方案3】:
      var man= new Private('170cm','60kg','26-year-old');
      

      创建一个对象名称 Private ,它允许 3 个字段:

       this.height
       this.weight
       this.age
      

      AND 一个调用函数的字段。这意味着如果您删除了this.recall=recall;,那么您将无法从man 调用recall

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-19
        • 2013-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-08
        • 2018-05-09
        • 1970-01-01
        相关资源
        最近更新 更多