动态属性访问

时间:2015-10-05 17:54:33

标签: javascript

试图找出一个主题,我无法接缝以使其发挥作用。这是代码:

<!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>

这不接缝工作,试图替换“返回这个[”说“+数字];”用“返回AGE [”说“+数字];”并且“返回[”说“+数字];”任何人都知道我错过了什么或弄乱了什么?

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

感谢保罗现在回答唯一的问题就是说,现在说2和说3都是公开的。

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());

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

2 个答案:

答案 0 :(得分:2)

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 ";
        }
    };
})();

答案 1 :(得分:0)

那些不是属性(任何东西,但肯定不是你要返回的匿名对象)。

将它们设为实际属性,并且有效:

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