Javascript 将键添加到工厂功能对象



如果这个问题在上一篇文章中得到回答,我深表歉意。我看了看,但没有发现类似的东西。我想知道是否有人知道我可以从工厂函数向结果对象添加键的方法。这意味着,在工厂函数之外,我想稍后添加一个键,而不是回到工厂函数本身并更改输出应该是什么。

/*below you will see where I have tried to add the key from the outside using the function name as the object name similiar to how one would with a standard object but the code below will return undefinded, my guess is because the object has no name, but rather is simply returned.*/
function createCharacter(name, nick, race, origin, attack, defense){
	return {
		name: name,
		nickname: nick,
		race: race,
		origin: origin,
		attack: attack,
		defense: defense,
		describe: function(){
			console.log(`${this.name} is a ${this.race} from ${this.origin}`);
		}
}
createCharacter.weapon = weapon;

您需要使用 new createCharacter() 创建函数的实例:

/*below you will see where I have tried to add the key from the outside using the function name as the object name similiar to how one would with a standard object but the code below will return undefinded, my guess is because the object has no name, but rather is simply returned.*/
function createCharacter(name, nick, race, origin, attack, defense){
	return {
		name: name,
		nickname: nick,
		race: race,
		origin: origin,
		attack: attack,
		defense: defense,
		describe: function(){
			console.log("${this.name} is a ${this.race} from ${this.origin}"+weapon);
		}
    }
}
x = new createCharacter()
x.weapon = "sword";
console.log(x.weapon);

如果继续使用 createCharacter 函数,请获取如下所示的 Character 实例:

function createCharacter(name, nick, race, origin, attack, defense){
    return {
        name: name,
        nickname: nick,
        race: race,
        origin: origin,
        attack: attack,
        defense: defense,
        describe: function(){
            console.log(`${this.name} is a ${this.race} from ${this.origin}`);
        }
   }
}
//just directly invoke factory function,which will return a Character instance
var oneCharacter = createCharacter();
oneCharacter.weapon = "weapon";

另一种方法是使用构造器,如下所示:

function Character(name, nick, race, origin, attack, defense){
    this.name = name;
    this.nick = nick;
    this.race = race;
    this.origin = origin;
    this.attack = attack;
    this.defense = defense;
    this.describe = function(){
            console.log(`${this.name} is a ${this.race} from ${this.origin}`);
        }
}
//use keyword "new" get a Character instance 
var oneCharacter = new Character();
oneCharacter.weapon = "weapon";

最新更新