我刚开始在js学习OOP。我的问题是,当你调用新函数('key')时,是否可以动态设置你的密钥?更清楚这里是我的榜样。
function Rabbit(type) {
this.type = type;
this.name = type+"Rabbit";
}
var cage = {};
cage.addAnimal( new Rabbit('fat') );
console.log(cage)
这会输出
cage{ fatRabbit: Rabbit{
type: 'fat',
name: 'fatRabbit',
__proto__: function() {...}
}
} //<-- Rabbit is the new Rabbit('fat')
如果我做错了,请告诉我。谢谢!
答案:
而不是
cage.addAnimal( new Rabbit('fat') );
我做的是:
var cage = {};
function Rabbit(type) {
this.type = type;
this.name = type+"Rabbit";
cage[this.name] = this;
}
new Rabbit('fat') // I simply call this and a new property is added on cage.
console.log(cage)
答案 0 :(得分:1)
是的,你可以使用bracket notation:
function Rabbit(type) {
this.type = type;
this.name = type+"Rabbit";
}
var cage = {
addAnimal: function(animal) {
this[animal.name] = animal;
}
};
cage.addAnimal( new Rabbit('fat') );
console.log(cage)