在这种情况下,我想创建动态新对象(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>