码迷,mamicode.com
首页 > Web开发 > 详细

JS继承

时间:2020-06-14 10:29:21      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:pre   struct   alert   let   call   xtend   end   js继承   cto   

ES5继承

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function () {
  alert(`My name is ${this.name}.`);
  return this.name;
}
Person.prototype.constructor = Person;

function Student(name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayGrade = function () {
  alert(`I am a grade ${this.grade} student.`);
  return this.grade;
}

let s1 = new Student("Mike", 12, 4);
let s2 = new Student("Helen", 18, 12);

ES6继承

class Person {
  constructor (name, age) {
    this.name = name;
    this.age = age;
  }
  sayName () {
    alert(`My name is ${this.name}.`);
    return this.name;
  }
}
class Student extends Person {
  constructor (name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
  sayGrade () {
    alert(`I am a grade ${this.grade} student.`);
    return this.grade;
  }
}
let s1 = new Student("Mike", 12, 4);
let s2 = new Student("Helen", 18, 12);

JS继承

标签:pre   struct   alert   let   call   xtend   end   js继承   cto   

原文地址:https://www.cnblogs.com/buildnewhomeland/p/13123907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!