Created
December 30, 2018 06:30
-
-
Save 7cc/a625cbf96f6f7cc3c74535953ede0858 to your computer and use it in GitHub Desktop.
create subclass in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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