What is the "extends" keyword in Spider?

156 views Asked by At

Spider embraces JavaScript prototype OOP by adding 2 keywords: extends and super.

  • What are they?
  • What problems do they solve?
  • When are they appropriate and when not?
1

There are 1 answers

0
Alon Gubkin On BEST ANSWER

The extends keyword allows you to inherit an existing object. For example, let's say you have an Animal object:

fn Animal(name) {
  this.name = name;

  this.walk = fn() {
    console.log('\(name) is walking...');
  };
}

Animal.prototype.getLegs = fn() {
  return 4;
};

You can now create another object that inherits Animal using the extends keyword:

fn Spider(name)
  extends Animal(name) {

}

Spider.prototype.getLegs = fn() {
  return 8;
};

When you create a new Spider object, you'll automatically have your walk method because Spider extends Animal.

var spider = new Spider("Skitter the Spider");
spider.walk();

Spider (the language) also provides the super keyword which allows you to easily access the object you are extending. For example:

Spider.prototype.getLegs = fn() {
  return super.getLegs() + 4; 
};

spider.getLegs(); // => 8

Implementation

This code in Spider:

fn Spider() extends Animal {}

compiles to the following JavaScript:

function Spider() {
  Animal.call(this);
}

Spider.prototype = Object.create(Animal);