Skip to content

Instantly share code, notes, and snippets.

@7cc
Created December 30, 2018 06:30
Show Gist options
  • Select an option

  • Save 7cc/a625cbf96f6f7cc3c74535953ede0858 to your computer and use it in GitHub Desktop.

Select an option

Save 7cc/a625cbf96f6f7cc3c74535953ede0858 to your computer and use it in GitHub Desktop.
create subclass in javascript
var Person = function(name) {
this.name = name;
};
Person.prototype.isHuman = true;
// subclass
var Boy = class Boy extends Person {
constructor(name, age) {
super(name);
this.age = age;
}
get sex() {
return "M";
}
};
// use getter or prototype.property
// Boy.prototype.sex = "M";
var Peter = new Boy("Peter", 13);
console.log(Peter.name); // "Peter"
console.log(Peter.age); // 13
console.log(Peter.sex); // "M"
console.log(Peter.isHuman); // true
var Person = function(name) {
this.name = name;
};
Person.prototype.isHuman = true;
// subclass
var Boy = function(name, age) {
Person.call(this, name); // 1
this.age = age;
};
Boy.prototype = Object.create(Person.prototype); // 2
Boy.prototype.constructor = Boy; // 3
Boy.prototype.sex = "M";
var Peter = new Boy("Peter", 13);
console.log(Peter.name); // "Peter"
console.log(Peter.age); // 13
console.log(Peter.sex); // "M"
console.log(Peter.isHuman); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment