【问题标题】:Adding Properties to existing Javascript Objects from Object Constructors从对象构造函数向现有 Javascript 对象添加属性
【发布时间】: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 取决于您所说的“稍后”究竟是什么意思以及如何调用该代码。
  • 谢谢罗伯特——我换了分号。

标签: javascript constructor


【解决方案1】:

您可以在事后添加其他属性:

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);
johnDoe.foo = "bar";

您正在使用函数构造函数模式,但请注意,根据您的用例,您可以使用其他一些 javascript 对象封装模式,其中一些模式比其他模式更好。在我看来,只有在使用 ES6 之前,我才会使用函数构造函数模式,如果使用 >=ES6 (ES2015),我会使用 class,并且仅当我需要一堆对象实例时。否则,如果只需要一个对象实例,我宁愿使用revealing module pattern。使用乐趣

没有用重新发明轮子,接受的答案和this question 的其他一些高度投票的答案给出了一个很好的总结。 This video 解释了在 javascript 中使用 this 的一些困惑,并提供了一种意见,即最好尽可能避免使用 this

【讨论】:

  • 应该注意还有其他方法可以做到这一点,例如构造函数中的设置器
  • 感谢您的回答。我是 OOP 的新手。我知道还有其他创建对象的模式,以及避免这种模式的充分理由,但我只是想确保我了解它在最基本的层面上是如何工作的。
猜你喜欢
  • 2021-03-31
  • 2019-11-24
  • 2018-07-24
  • 2018-10-23
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
相关资源
最近更新 更多