1-1 class定义一个简单的类

  1. class Person{
  2. constructor(name,age){
  3. this.name = name;
  4. this.age = age
  5. }
  6. }

直接定义在class中的属性,还是实例私有的属性。

  1. class Person{
  2. skill = "javascript"
  3. constructor(name,age){
  4. this.name = name;
  5. this.age = age
  6. }
  7. }
  1. console.log(p.hasOwnProperty("skill"))

1-2 共有方法

  1. class Person {
  2. constructor(name, age) {
  3. this.name = name;
  4. this.age = age
  5. }
  6. sayName(){
  7. console.log(this.name)
  8. }
  9. }
  10. var p = new Person("cheng", 18);
  11. p.sayName()

1-3 添加共有的方法

  1. Object.assign()

es6不支持使用直接量的方式在原型上添加

  1. class Person {
  2. constructor(name, age) {
  3. this.name = name;
  4. this.age = age
  5. }
  6. sayName() {
  7. console.log(this.name)
  8. }
  9. }
  10. Person.prototype = {
  11. sayAge() {
  12. console.log(this.age)
  13. }
  14. }
  15. # 会报错
  1. class Person {
  2. constructor(name, age) {
  3. this.name = name;
  4. this.age = age
  5. }
  6. sayName() {
  7. console.log(this.name)
  8. }
  9. }
  10. Object.assign(Person.prototype,{
  11. sayAge(){
  12. console.log(this.name)
  13. },
  14. saySkill(){
  15. console.log("前端")
  16. }
  17. })
  18. var p = new Person("cheng",16);
  19. p.sayAge()

1-4 继承

  1. class Person{
  2. constructor(name,age){
  3. this.name = name;
  4. this.age = age
  5. }
  6. sayName(){
  7. console.log(this.name);
  8. }
  9. }
  10. class Teacher extends Person{
  11. // 类继承之后,构造函数第一行必须写super关键字,去继承父类的属性
  12. constructor(name,age,skill){
  13. super(name,age)
  14. this.skill = skill
  15. }
  16. // 在子类的方法中调用父类的方法 (this或super去调用)
  17. show(){
  18. super.sayName()
  19. // this.sayName()
  20. }
  21. }
  22. var t = new Teacher("zhang",18,"js")
  23. console.log(t);
  24. t.sayName()