gpt4 book ai didi

Javascript 将 key 添加到工厂函数对象

转载 作者:行者123 更新时间:2023-12-03 04:21:52 24 4
gpt4 key购买 nike

如果这个问题已在上一篇文章中得到解答,我深表歉意。我看了看,但没有找到类似的东西。我想知道是否有人知道如何将 key 添加到工厂函数的结果对象中。意思是,在工厂函数之外,我想稍后添加一个键,而不是返回到工厂函数本身并更改输出应该是什么。

/*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);

关于Javascript 将 key 添加到工厂函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com