gpt4 book ai didi

javascript - 动态属性访问

转载 作者:行者123 更新时间:2023-12-02 15:35:48 25 4
gpt4 key购买 nike

试图找出一个主题,但我无法让它发挥作用。这是代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Experiments</title>
</head>
<body>
<script>
var AGE = (function(){
var saying1 = "this is saying 1 ";
var saying2 = "this is saying 2 ";
var saying3 = "this is saying 3 ";

return {
say: function(numbers){
return this["saying" + numbers];
},
sayFunction: function(){
return "Hello World ";
}

};
})();
document.write(AGE.sayFunction());
document.write(AGE.say(1));
document.write(AGE.say(2));
document.write(AGE.say(3));

</script>
</body>
</html>

这似乎不起作用,尝试替换“返回这个[“说”+数字];”与“返回年龄[“说”+数字];”和“返回[“说”+数字];”有人知道我错过了什么或搞砸了什么吗?

var AGE = (function() {
return {
saying1: "this is saying 1",
saying2: "this is saying 2 ",
saying3: "this is saying 3 ",

say: function(numbers) {
return this["saying" + numbers];
},

sayFunction: function() {
return "Hello World ";
}
};
})();

console.log(AGE.sayFunction());
console.log(AGE.say(1));
console.log(AGE.say(2));
console.log(AGE.say(3));

感谢 Paul 的回答,现在唯一的问题是 said1、say2 和 Saying3 现已公开。

var AGE = (function(){
var say1 = "this is saying 1 ";
var say2 = "this is saying 2 ";
var say3 = "this is saying 3 ";

return {
say: function(){
return say1;
}
};
})();
document.write(AGE.say());

这是我试图实现的效果,但使用括号表示法,我现在不知道“动态属性访问”是否可以通过公共(public)函数进行私有(private)访问?

最佳答案

sayings 不在 this 中,它们是作用域的局部变量,我建议改为创建一个映射:

var AGE = (function(){
var sayings = {
1: "this is saying 1 ",
2: "this is saying 2 ",
3: "this is saying 3 "
};

return {
say: function(numbers){
return sayings[numbers];
},
sayFunction: function(){
return "Hello World ";
}
};
})();

关于javascript - 动态属性访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954849/

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