【问题标题】:Understanding 'this' placement in JavaScript when creating an object在创建对象时了解 JavaScript 中的“this”位置
【发布时间】:2018-10-24 04:31:09
【问题描述】:

我试图理解为什么函数 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;
}

例如,如果等号后面的名称指向“苹果” 并且 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' 吗?

【问题讨论】:

标签: javascript object this


【解决方案1】:

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

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访问属性

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

【讨论】:

  • 我没有这个我可以格式化我的评论,所以我会把它添加到问题中!感谢您的详细说明。
  • @user64350 如果您使用name 定义函数的参数,则您似乎对函数参数是什么以及对象属性是什么有点误解,只要您想访问您使用的参数@987654329 @,当您使用this.name 时,您正在尝试访问一个名为 name 的属性
  • 感谢您详细说明这两个误解。我认为它有很大帮助!
  • @user64350 欢迎您,如果您觉得答案有帮助,您可以投票/接受吗?
  • 我距离在 StackOverflow 上投票还差一分!对这一切还是很陌生:)
【解决方案2】:

之所以只有第一种方式是因为赋值运算符 = 将右侧分配给左侧,而不是引用。

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2023-03-13
    • 2012-08-29
    相关资源
    最近更新 更多