我想在這種情況下創建動態新對象(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>
我猜你應該寫:this.gameAnimals [I]的.init = this.init ;所以沒有()哪個調用函數 – philipp 2013-04-25 08:55:28
我會試試看謝謝。 – user1954217 2013-04-25 08:58:24