javascript - How to inheritance function from the main object to other objects dynamic? -
i want create dynamic new objects (someanimal) in case example frog
under object 'game
'.
inside game.frog
want inheritance game
function init frog
frog have function init
, other animals clone function init
.
game.frog.init(), game.lion.init() ...... game.n...int()
the animal below
many help.
game.frog = { init: function(){ this.property1 = something; this.property2 = something; this.property3 = something; this.property1000 = something; } };
my code:
<!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 = 0; < gameanimals.length; i++){ this.gameanimals[i] = {}; this.gameanimals[i].init() = this.init(); //or //gameanimals[i].prototype = new game(); // someanimal inheritance 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>
you should reconsider way trying access "animals"... try this:
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); };