2

我一直在对对象文字等进行一些研究。我正在创建一个具有来自我的玩家的各种属性的游戏。这些属性存储在多个组中,例如他的船和所有属性,他的武器和所有属性等。因此,我一直将这些属性存储到对象文字中。

我不希望我的对象值被覆盖。我在这里遇到了一篇文章http://www.gabordemooij.com/jsoop.html,并且很好奇这样的事情是否会是一个健康的开始,以防止对象值被轻易覆盖......

Cat = {
  createNew: function() {
    var cat = {};
    var sound = "meow"; //sound is local
    cat.makeSound= function(){
        //can reach sound from here
        alert( sound );
    }
    return cat;
  }
}

var cat = Cat.createNew();
cat.makeSound();
//but can't reach sound from here
alert(cat.sound); //fail!
4

2 回答 2

1

我在jsFiddle中设置了一个小测试来演示显示对象模式是多么美妙的事情:

var Test = (function(){
    var priv = "Banana";
    var public = "Orange";
    var pubobj = {name:"Cheese"};

    function constructor(){
        this.public = public;
        this.pubobj = pubobj;

        this.instance = {name:"Grape"};

        this.instanceMethod = function(){
            return priv;
        };
    };

    constructor.prototype.private = function(){
        return priv;
    };            

    return constructor;

})();

var myTest = new Test();

console.log(myTest.public);     //Orange
console.log(myTest.priv);       //undefined
console.log(myTest.private());  //Banana

var myTest2 = new Test();

console.log(myTest.public === myTest2.public);    //true (they are both primitives with the same value)
console.log(myTest.private === myTest2.private);  //true (the methods share the same instance)

myTest.public = "cheese";
console.log(myTest.public, myTest2.public);       // "cheese", "Orange" (overwriting the primitive doesn't change the primitive of myTest2)

myTest.pubobj.name = "Melon";                   
console.log(myTest.pubobj, myTest2.pubobj);       //the name property for both is now "Melon" (both test objects share the same instance of pubobj)

myTest.instance.name = "Raspberry";
console.log(myTest.instance, myTest2.instance);  // the name of myTest2.instance is unchanged

console.log(myTest.instanceMethod === myTest2.instanceMethod);​  // false (while identical, these methods have separate instances)
于 2012-09-28T21:46:16.057 回答
0

它失败了,因为声音是一个不能在对象外部引用的局部变量。

如果你想引用它,你需要做一个getter。

Cat = {
  createNew: function() {
    var cat = {};
    var sound = "meow"; //sound is local
    cat.getSound= function(){
        //can reach sound from here
        return sound;
    }
    return cat;
  }
}


var cat = Cat.createNew();
alert(cat.getSound());

或者

Cat = {
  createNew: function() {
    var cat = {};

    var props = {
        sound : "meow",
        foo : "bar"
    };

    cat.get= function(key){            
        return props[key];
    }
    return cat;
  }
}

var cat = Cat.createNew();
alert(cat.get("sound"));
于 2012-09-28T21:36:34.243 回答