这在JavaScript函数中引用了什么? [英] What does this refer to in a JavaScript function?

查看:166
本文介绍了这在JavaScript函数中引用了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数Box(width,height)
{
this.width = width;
this.height = height;
}

var myBox = new Box(5,5);




  1. 什么是关键字在技术上做这里?它创造了一个新的功能吗?或者是它创建一个新的对象并将其应用到它?

  2. 如果是这样,这是创建一个盒子的方式,这是否意味着这个关键字实际上是指对象myBox?使用创建一个新对象,使用 Box 作为其构造函数。在这种情况下, 的值(当 new >关键字调用函数时)是正在构建的新实例。这个新对象将继承任何被定义为 Box.prototype (默认为 Object.prototype )。 p>

    我在这种情况下说 ,因为在JavaScript中, this 的值取决于该函数被调用。我建议您阅读 MDN页面> 以获得更多信息。






    注意:如果这个问题出现要关闭,它应该是重复的。以下是一些可能会对您有帮助的重复链接: / javascript-this-keyword>this关键字工作?

  3. Javascript的'这个'值改变,但无法弄清楚为什么


  4. javascript this object

  5. 这个关键字在函数中工作?


  6. function Box(width, height)
    {
      this.width = width;
      this.height = height;
    }
    
    var myBox = new Box(5,5);
    

    1. What is the new keyword doing here technically? Is it creating a new function? Or is it creating a new object and applying the function to it?

    2. If so then this is a way to create a "Box", does this mean the this keyword is actually referring to the object myBox?

    解决方案

    It's creating a new object, using Box as its constructor. The value of this in this case (when the function is called with the new keyword) is the new instance being constructed. This new object will inherit from whatever is defined as Box.prototype (the default being Object.prototype).

    I said in this case, because in JavaScript the value of this is determined by how the function is called. I recommend reading the MDN page on this for more information.


    Note: if this question is supposed to be closed, it should have been as a duplicate. Here are some possible duplicate links that might also help you:

    这篇关于这在JavaScript函数中引用了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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