首页 > 解决方案 > 在创建对象时了解 JavaScript 中的“this”位置

问题描述

我试图理解为什么函数 Fruit 在制作对象时起作用:

function Fruit(name, color, shape){
    this.name = name;
    this.color = color;
    this.shape = shape;
}

var apples = new Fruit('apple', 'red', 'round');

为什么不是以下内容:

function Fruit(name, color, shape){
   name = this.name;
   color = this.color;
   shape = this.shape;
}

例如,如果等号后面的名称是指向“apple”的内容,而 this 指向 var apples 中的参数,将其放在后面不是更有意义吗?

如果我没有正确表达问题,请提前道歉。


为了澄清为什么我不明白,让我们更改名称,使它们不一样:

 function Fruit(name, color, shape){
     this.thename = name;
     this.thecolor = color;
     this.theshape = shape;
 }

var apples = new Fruit('apple', 'red', 'round');

这仍然有效,因为对象 apples 将是 {thename: 'apple', thecolor: 'red', theshape: 'round'}

那么如果你在函数中有 thename = this.name 那不是 thename = 'apple' 吗?

标签: javascriptobjectthis

解决方案


为了澄清你的建议(编辑以匹配你的编辑),如果我们有这样的功能:

function Fruit(name, color, shape){
    thename = this.name;
    thecolor = this.color;
    theshape = this.shape;
}

然后打电话

var apples = new Fruit('apple', 'red', 'round');

将意味着:

thename = this.name
thecolor = this.color
theshape = this.shape

现在您正在尝试将不存在的属性存储到变量中,这些变量在调用函数后将不会被访问,并且最终可能会被垃圾收集。在这种情况下,结果将没有属性,并且不会保存传递给它的任何数据。

您的误解是name使用this.name而不是访问函数的参数name,这里澄清一下:

  • 使用在函数初始定义期间分配给它们的任何名称来访问函数的参数
  • 属性通过调用访问this.attribute

这种区别是为了清楚您是使用属性还是使用参数。


推荐阅读