2015-10-05 71 views
0

試圖找出一個主題,我無法縫合讓它工作。這裏是代碼:動態財產訪問

<!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 [」說「+數字」);「和「return [」說「+數字」);「任何人都知道我失蹤或弄亂了什麼?

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

謝謝保羅現在唯一的問題是說1,說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()); 

這就是我想實現但括號記號我現在不知道是否「動態屬性訪問權限」,可以通過公共職能與私人訪問工作有何影響?

+1

'this'在您使用它的上下文中無效。更重要的是,你似乎對JS中原型/類的工作方式感到困惑。我的建議是在網上搜索一些教程,你可能會自己想出來。 – doogle

回答

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

+0

這就是我想要的方式,但是說1,說2和說3不再是私人的。在我以前的代碼中,我可以返回任何私有成員,例如。 「return saying1」但不能使用動態括號表示法,例如。 「return [」說「+」ing「+ 1]」 – abflett

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

謝謝,我知道這將工作,但我正在使用括號表示動態屬性,並將它調味一點,我保持會員私密。 – abflett

+0

成員仍然是私人的。你可以改變說法對象的屬性名稱,使其符合你在做它的方式,它也可以工作。 – taxicala