在本例中我想创建动态新对象 (someAnimal),例如对象“Game
”下的 frog
。
在Game.frog
内部我想从Game
继承函数init到frog
所以 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>
最佳答案
你真的应该重新考虑你试图接触你的“动物”的方式...... 试试这个:
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);
};
关于javascript - 如何将函数从主对象动态继承到其他对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210254/