javascript - 如何将函数从主对象动态继承到其他对象?

标签 javascript object inheritance

在本例中我想创建动态新对象 (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/

相关文章:

javascript - 将 Google Charts 中的日期时间数据更改为 24 小时格式

javascript - 比较JS中的两个对象属性

javascript - CoffeeScript 中执行错误的事件

javascript - 如何将 div 放置在 100% 宽度的图像上?

swift - 如何在 Swift 类内部的函数中使用类名

c++ - 无效的协变返回类型错误

c++ - 显式类型标识符与 RTTI

java - java中的静态方法和实例方法-父类和子类

javascript - CSS 3 Flexbox 模型宽度 jQuery

oop - OCaml 中对象内的对象