javascript - 对对象中的方法和属性使用相同的变量
问题描述
经过 1 小时试图弄清楚如何让它发挥作用后,我放弃了,决定在这里问。
所以我创建了一个对象:
var potion1 = {
color: "red",
effect: "strength",
duration: 1+" minute",
price: 10,
test: function() {
return "test good"
}
}
我正在做的是要求输入并显示相应的文本。
var x = prompt();
x = document.getElementById("potions").innerHTML="Potion 1 : " + potion1[x];
问题是颜色,效果,持续时间,价格一切正常,但测试回报function() { return "test good" }
如果我使用x = document.getElementById("potions").innerHTML="Potion 1 : " + potion1[x]();
测试工作正常,但所有其他人都没有返回
所以我想知道 x 是否可以使用颜色、效果、持续时间、价格和测试。
解决方案
你可以做test
一个吸气剂。
var potion1 = {
color: "red",
effect: "strength",
duration: 1 + " minute",
price: 10,
get test() {
return "test good"
}
}
推荐阅读
- javascript - Bugsnag 错误 UnhandledRejection - 拒绝原因不是错误
- c - 使用变量作为函数参数和直接使用字符串作为函数参数有什么区别?
- c#-4.0 - c#将数组中的随机结果分配给变量返回超出范围的错误
- r - 将 ascii 或二进制网格数据导入 R
- react-native-firebase - 使用 Firebase 将 React Native Firebase 集成到现有的 iOS 应用程序中
- php - 如何在 Laravel Blade 中添加多个子行数据和父行
- c# - 如何在 Entity Framework 6 中创建字段并从连接表中获取数据
- python-3.x - 从 .csv 导入 Dataframe 导入为 OBJECT 而不是 FLOAT
- c++ - 返回值的 const 引用是什么?
- c - SELECTION SORT - 我自己的排序版本