这在JavaScript函数中引用了什么? [英] What does this refer to in a JavaScript function?
问题描述
函数Box(width,height)
{
this.width = width;
this.height = height;
}
var myBox = new Box(5,5);
-
什么是
新
关键字在技术上做这里?它创造了一个新的功能吗?或者是它创建一个新的对象并将其应用到它? 如果是这样,这是创建一个盒子的方式,这是否意味着 - Javascript的'这个'值改变,但无法弄清楚为什么
- javascript this object
- 这个关键字在函数中工作?
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?If so then this is a way to create a "Box", does this mean the
this
keyword is actually referring to the object myBox?- How does the "this" keyword work?
- Javascript 'this' value changing, but can't figure out why
- this value in JavaScript anonymous function
- javascript this object
- How does "this" keyword work within a function?
这个
关键字实际上是指对象myBox?使用创建一个新对象,使用 Box
作为其构造函数。在这种情况下, 的值(当 new >关键字调用函数时)是正在构建的新实例。这个新对象将继承任何被定义为 Box.prototype
(默认为 Object.prototype
)。 p>
我在这种情况下说 ,因为在JavaScript中, this
的值取决于该函数被调用。我建议您阅读 MDN页面>
以获得更多信息。
注意:如果这个问题出现要关闭,它应该是重复的。以下是一些可能会对您有帮助的重复链接: / javascript-this-keyword>this关键字工作?
function Box(width, height)
{
this.width = width;
this.height = height;
}
var myBox = new Box(5,5);
解决方案 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屋!