开发者

Can anyone tell the correct way of forming this code and using it

开发者 https://www.devze.com 2023-03-17 11:47 出处:网络
var hash = { func1: function(){ 开发者_StackOverflow}, return { contains: function(key) { return keys[key] === true;
var hash = {     
     func1: function(){

开发者_StackOverflow     },
     return {         
        contains: function(key) {
        return keys[key] === true;         
     },
        add: function(key) {
             if (keys[key] !== true){
             keys[key] = true;             
         }
     }      
} 

Can anyone explain me how the return works here... Can i call hash.contains(key) I feel the code what i have written is wrong... mean the structure?


var hash = (function () {
    var keys = {};
    return {
        contains: function (key) {
            return keys[key] === true;
        },
        add: function (key) {
            if (keys[key] !== true) {
                keys[key] = true;
            }
        }
    }
})();

That is what I think you were trying to achieve. From your code I thought you were trying to create a hash object with a add and contains method for checking if keys exisist within your keys var but also making it a protected variable.

What the above code does is create a closure that contains the keys variable (an object) and returns an object with the two methods contains and add.

You can read more about closures here http://jibbering.com/faq/notes/closures/. Closures are one of the biggest reasons Javascript is as flexible as it is.


I'm unsure why you would need such a hash object as the Javascript language has hash objects built-in already and they would be much faster. You can do this with plain Javascript:

var team = {};
team.sport = "baseball";
team.city = "San Francisco";
team.name = "San Francisco Giants";
team.lastChampionship = 2010;
team.currentStanding = 1;

if (team.sport) {                                  // contains test
  alert("This team plays " + team.sport);
}

or this:

var playerNames = {};
playerNames["Zito"] = "pitcher";
playerNames["Lincecum"] = "pitcher";
playerNames["Cain"] = "pitcher";
playerNames["Sandoval"] = "infielder";
playerNames["Posey"] = "catcher";

if (playerNames["Posey"]) {                         // contains test
  alert("Posey is a " + playerNames["Posey"]);
} else {
  alert("No player by the name of Posey");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消