[英]How to add a new property to constructor function using the this keyword?
我想在我的構造函數中添加一個帶有'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;
}
有任何想法嗎? 還是這樣不行?
如果要在運行時向構造函數添加屬性,可以通過將其添加到構造函數原型中來實現
例如
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.