2013-04-25 35 views
0

我想在這種情況下創建動態新對象(someAnimal),例如對象'Game'下的frog如何從主對象向其他對象動態繼承功能?

裏面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> 
+1

我猜你應該寫:this.gameAnimals [I]的.init = this.init ;所以沒有()哪個調用函數 – philipp 2013-04-25 08:55:28

+0

我會試試看謝謝。 – user1954217 2013-04-25 08:58:24

回答

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

非常感謝..... – user1954217 2013-04-25 10:04:56

1

爲什麼不創建一個動物功能,然後你就可以實例爲每個小動物:

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繼承模式的一些想法。