What is the "extends" keyword in a Spider?
The keyword extends
allows you to inherit from an existing object. For example, suppose you have an object Animal
:
fn Animal(name) {
this.name = name;
this.walk = fn() {
console.log('\(name) is walking...');
};
}
Animal.prototype.getLegs = fn() {
return 4;
};
Now you can 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 object Spider
, you will automatically get your method walk
, because Spider
extends Animal
.
var spider = new Spider("Skitter the Spider");
spider.walk();
The spider (language) also provides a keyword super
that allows you to easily access the object you are distributing. For example:
Spider.prototype.getLegs = fn() {
return super.getLegs() + 4;
};
spider.getLegs(); // => 8
Implementation
This code in Spider:
fn Spider() extends Animal {}
the following JavaScript is compiled:
function Spider() {
Animal.call(this);
}
Spider.prototype = Object.create(Animal);
source to share