【发布时间】:2019-04-20 02:40:59
【问题描述】:
在 Javascript 中创建对象构造函数时,我知道有必要在属性名称前加上 'this' 关键字。
function funcConstruct(first,last,age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.fullNameAge = function() {
return this.lastName + ', ' + this.firstName + ', ' + this.age
};
};
var johnDoe = new funcConstruct('John', 'Doe', 52);
console.log(johnDoe.fullNameAge());
Doe, John, 52
如果您希望稍后为对象添加其他属性,是否需要使用 'this' 关键字,如果需要,它在语法中的什么位置?
【问题讨论】:
-
johnDoe.foo = 'bar';。此外,虽然逗号在语法上不是无效的,但用它结束语句并不是一个好习惯。请改用分号。 -
您是否需要使用
this取决于您所说的“稍后”究竟是什么意思以及如何调用该代码。 -
谢谢罗伯特——我换了分号。