简体   繁体   中英

How can I override superclass in JavaScript

I have a superclass here:

// 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);
};

This basically sets a walker span that walks a character. class walker has its own CSS. And now what I want to attain is to override its CSS as well as its position (bottom and right) so what I did is that on my new instance I put on a new node with a class runner that has its own CSS too and apply the arguments to the instance superclass but this doesn't override what I have on the superclass on this new instance.

// 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);
};

Any idea what am I doing wrong? How can I also override the position such as the bottom and right?

Change the subclass constructor to...

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

Notice that I swapped the order, so you override this.$node after calling super. Before you were declaring this.$node and then calling the constructor (with the same this ) and it was overriding what you had just set in this.$node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM