【问题标题】:I want to clone a javascript class. add methods to the cloned property without actually overwriting the exisiting methods?我想克隆一个 javascript 类。将方法添加到克隆属性而不实际覆盖现有方法?
【发布时间】:2012-05-16 21:28:48
【问题描述】:

我正在尝试将方法添加到克隆的原型类属性。我已经粘贴了下面的代码。

当我向这个 sn-p 代码添加方法时,它会覆盖超类中定义的内容。

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
var Animal = Class.create({
    initialize: function(name, sound) {
    this.name  = name;
    this.sound = sound;
    },

    speak: function() {
    alert(this.name + " says: " + this.sound + "!");
    }
});

Animal.movement = {
    move: function(direction){
        alert('moving: ' + direction)
    }
}

var AnimalClone = { }
Object.extend(AnimalClone, Animal);

//Now i want to add 'jump' to this list of methods 
//without over writing the inherited 'move' method
AnimalClone.movement = {
    jump: function(height){
        alert('jumped:' + height)
    }
}
</script>

【问题讨论】:

    标签: javascript oop inheritance prototypejs


    【解决方案1】:

    由于movement 是一个对象,您还必须通过使用原型访问它来扩展它

    var Animal = Class.create({
        initialize: function(name, sound) {
            this.name = name;
            this.sound = sound;
        },
        movement: {
            move: function(direction) {
                alert('moving: ' + direction);
            }
        }
    });
    
    var AnimalClone = Class.create({});
    AnimalClone.prototype = Object.extend(new Animal(),{});
    
    AnimalClone.prototype.movement = Object.extend(AnimalClone.prototype.movement, {
            jump: function(height) {
                alert('jumped:' + height);
            }
    });
    
    var animalClone = new AnimalClone;
    animalClone.movement.move("up");
    animalClone.movement.jump("10mts");
    

    【讨论】:

      【解决方案2】:

      您需要扩展 movement 对象,而不是覆盖它:

      Object.extend(AnimalClone.movement, {
          jump: function(height){
              alert('jumped:' + height)
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 2013-03-06
        • 1970-01-01
        • 2018-04-28
        相关资源
        最近更新 更多