【发布时间】: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' 吗?
【问题讨论】:
-
来自MDN: "基本的赋值运算符是相等的(
=),将其右操作数的值赋给左操作数" -
@user64350 我已经编辑了我的答案以匹配您当前的编辑,看看它
标签: javascript object this