如何在JavaScript中覆盖超类

时间:2018-01-10 23:07:20

标签: javascript

我在这里有一个超类:

// SUPERCLASS
var toWalk = function(bottom, right, space) {
  this.$node = $('<span class="walker"></span>');
  this.space = space;
  this.step();
  this.setPosition(bottom, right);
};

toWalk.prototype.step = function() {
  setTimeout(this.step.bind(this), this.space);
};

toWalk.prototype.setPosition = function(bottom, right) {
  var styleSettings = {
    bottom: bottom,
    right: right
  };

  this.$node.css(styleSettings);
};

这基本上设置了一个步行角色的助行器。 class walker有自己的CSS。而现在我想要实现的是覆盖它的CSS以及它的位置(底部和右边),所以我所做的就是在我的新实例上我放置了一个带有类跑步者的新节点,它也有自己的CSS并且适用实例超类的参数,但这不会覆盖我在这个新实例上的超类上的内容。

// SUBCLASS

var toRun = function(bottom, right, space) {
  this.$node = $('<span class="runner"></span>');
  toWalk.apply(this, arguments);
};


toRun.prototype = Object.create(toWalk.prototype);

toRun.prototype.constructor = toRun;

toRun.prototype.step = function() {
  toWalk.prototype.step.call(this);

  this.$node.toggleClass('size');

};

toWalk.prototype.setPosition = function(bottom, right) {
  var styleSettings = {
    bottom: bottom,
    right: right
  };

  this.$node.css(styleSettings);
};

知道我做错了什么吗?我怎样才能覆盖底部和右边的位置?

1 个答案:

答案 0 :(得分:2)

将子类构造函数更改为...

var toRun = function(bottom, right, space) {
  toWalk.apply(this, arguments);
  this.$node = $('<span class="runner"></span>');
};

请注意,我交换了订单,因此您在调用超级后覆盖this.$node 。在您声明this.$node然后调用构造函数(具有相同的this)之前,它覆盖了您在this.$node中设置的内容