javascript - 在创建对象时了解 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' 吗?
解决方案
为了澄清你的建议(编辑以匹配你的编辑),如果我们有这样的功能:
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
这种区别是为了清楚您是使用属性还是使用参数。
推荐阅读
- google-bigquery - BigQuery 中的递归计算
- c# - DataContract 版本控制
- javascript - HTML JS 手动表单验证不起作用
- assembly - 具有可变 nasm 长度的 2 个数组的标量积
- java - 当我使用 String 构造函数将 byte[] 转换为 String 时,SonarCloud 代码有异味
- javascript - 在Vue Native中单击按钮后如何禁用它?
- sql-server - 将数据插入 sql 表并获取最近插入的 iD 并将数据从不同表插入到同一表中
- android - 单击 View Pager 内的单选按钮移动到下一张幻灯片
- c# - Paint Event e.Graphics.DrawImage 似乎没有遵循双缓冲
- ios - 使用 Apple Wallet NFC Pass 作为 NFC 标签