0

在这种情况下,我想创建动态新对象(someAnimal),例如frog在对象“ Game”下。

在里面Game.frog我想从Game函数 init 继承到frog 所以青蛙也会有函数init ,所有其他动物都会克隆这个函数init

 Game.frog.init(), Game.lion.init() ...... Game.n...int()

动物将如下所示

非常感谢您的帮助。

Game.frog = {
    init: function(){
        this.property1 = something;
        this.property2 = something;
        this.property3 = something;
        this.property1000 = something;
    } 
};

我的代码:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var Game = {
    init: function(){
        this.property1 = 1;
        this.property2 = 2;
        this.property3 = 3;
        this.property1000 = 1000;
    },

     cons: function(gameAnimals){

        for(var i = 0; i < gameAnimals.length; i++){
             this.gameAnimals[i] = {};
             this.gameAnimals[i].init() = this.init();
            //or         
            //gameAnimals[i].prototype = new Game();        // someAnimal inheritance from Game 
            //gameAnimals[i].prototype.constructor=gameAnimals[i];      // frog constructor
        }
     }    
};

var gameAnimals = ['frog', 'lion', 'cat'];
Game.cons(gameAnimals);
alert(Game.frog[0]+' '+Game.frog[1]+' '+Game.frog[2]+' '+Game.frog[2]);//display  1 2 3 1000
                                                                        //frog.property2 = 2;
                                                                        //frog.property3 = 3;
                                                                        //frog.property1000 = 1000;
}//]]>  

</script>


</head>
<body>


</body>


</html>
4

2 回答 2

1

为什么不创建一个 Animal 函数,然后您可以为每个小动物实例化它:

function Animal() {
    self = this;
    self.init = function() {
        self.property1 = 1;
        self.property2 = 2;
        self.property3 = 3;
        self.property1000 = 1000;
    }
}

var frog = new Animal();
frog.init();

也可以阅读以下内容:http ://www.crockford.com/javascript/inheritance.html 以获得一些关于 JS 继承模式的想法。

于 2013-04-25T09:51:41.103 回答
1

你真的应该重新考虑你试图访问你的“动物”的方式......试试这个:

window.onload = function () {

    function Animal(name) {
      this.name = name;
      this.property1 = 1;
      this.property2 = 2;
      this.property3 = 3;
      this.property1000 = 1000;
    }

    function Game() {
      this.animals = {};

      this.addAnimal = function (animalName) {
        this.animals[animalName] = new Animal(animalName);

      };
    }


    var game = new Game();

    game.addAnimal('frog');
    game.addAnimal('lion');
    game.addAnimal('cat');

    alert(game.animals.frog.name +"; " + game.animals.frog.property1 +"; " + game.animals.frog.property2);
  };
于 2013-04-25T09:57:25.880 回答