如何使用this关键字向构造函数添加新属性?

时间:2019-06-24 19:21:52

标签: javascript

我想在我的构造函数中添加一个带有'this'关键字的新属性,但我不知道该怎么做。

function Dog(name, age) {
    this.name = name;
    this.age = age; 
}

我想要这样的东西:

Dog['this.type'] = type;

console.log(Dog);

function Dog(name, age) {
    this.name = name;
    this.age = age; 
    this.type = type;
}

有什么想法吗?还是这样行不通?

1 个答案:

答案 0 :(得分:-1)

如果要在运行时向构造函数添加属性,可以通过将其添加到构造函数原型中来实现

例如

function Dog(name, age) {
    this.name = name;
    this.age = age;
}

const dog = new Dog('dog', 2);

Dog.prototype.greet = function(){
    console.log(`hello from ${this.name}, that is ${this.age} years old`);
} 

dog.greet() // prints hello from dog, that is 2 years old