Skip to content

Instantly share code, notes, and snippets.

@sylingd
Last active December 15, 2018 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylingd/0a148f61944ca372b55faab56b9e4cfb to your computer and use it in GitHub Desktop.
Save sylingd/0a148f61944ca372b55faab56b9e4cfb to your computer and use it in GitHub Desktop.
JavaScript extend demo
function People (name) {
this.name = name;
}
People.prototype.getName = function() {
return this.name;
}
function Student(name) {
People.call(this, name);
this.learn = function() {
console.log(`Student ${this.getName()} is learning`);
}
}
Student.prototype = Object.create(People.prototype);
Student.prototype.constructor = Student;
function CollegeStudent(name, department) {
Student.call(this, name);
this.department = department;
this.learn = function() {
console.log(`College student ${this.getName()} from ${this.department} is learning`);
}
this.goLibrary = function() {
console.log(`College student ${this.getName()} go to library`);
}
}
CollegeStudent.prototype = Object.create(Student.prototype);
CollegeStudent.prototype.constructor = CollegeStudent;
function MiddleSchoolStudent(name, grade) {
Student.call(this, name);
this.grade = grade;
}
MiddleSchoolStudent.prototype = Object.assign(Object.create(Student.prototype), {
constructor: MiddleSchoolStudent,
learn: function() {
console.log(`Middle school student ${this.getName()} from grade ${this.department} is learning`);
}
});
var p1 = new CollegeStudent("Jack", "CS");
console.log(p1.getName());
p1.goLibrary();
var p2 = new MiddleSchoolStudent("Jason", 1);
console.log(p2.getName());
p2.learn();
class People {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Student extends People {
constructor(name) {
super(name);
}
learn() {
console.log(`Student ${this.getName()} is learning`);
}
}
class CollegeStudent extends Student {
constructor(name, department) {
super(name);
this.department = department;
}
learn() {
console.log(`College student ${this.getName()} from ${this.department} is learning`);
}
goLibrary() {
console.log(`College student ${this.getName()} go to library`);
}
}
var p = new CollegeStudent("Jack");
console.log(p.getName());
p.goLibrary();
class Demo {
get name() {
return this._name;
}
set name(v) {
this._name = v.substr(0, 5);
}
}
var d = new Demo();
d.name = 'Jackson';
console.log(d.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment