JavaScript基础学习-class

class

es6中新增了class,可以更好的使用类和继承的设计模式,含有super语法糖,可以实现类的继承,方法的重写。
方法不需要写function关键字
不能声明属性,只可以声明方法
可以继承内部对象,比如Array

  class A {
    constructor(name) {
      this.name = name;
    }

    sayHello() {
      console.log(`hello ${this.name}`);
    }

    saySeeYou() {
      console.log('see you');
    }
  }

  class B extends A {
    constructor(name, age) {
      super(name);
      this.age = age;
    }

    sayHello() {
      super.sayHello();
      console.log(`age ${this.age}`);
    }
  }

  var a = new A('jsong');
  a.sayHello(); // hello jsong
  var b = new B('jsong', '11');
  b.sayHello(); // hello jsong
  // age 11

  b.saySeeYou(); // see you
es5写法

表面上es6的类写法和java很相似,但是类和子类和对象之间的关系仍然是原型委托的关系,没有类的复制。只不过在内部实现了繁琐的js的类的写法,让我们更轻松的使用类。
es5写法

  function A(name) {
    this.name = name;
  }
  A.prototype.sayHello = function() {
    console.log(`hello ${this.name}`);
  };
  A.prototype.saySeeYou = function() {
    console.log('see you');
  };

  function B(name, age) {
    A.call(this, name);
    this.age = age;
  }
  B.prototype = Object.create(A.prototype);
  B.prototype.sayHello = function() {
    A.prototype.sayHello.call(this);
    console.log(`age ${this.age}`);
  };

  var a = new A('jsong');
  a.sayHello(); // hello jsong
  var b = new B('jsong', '11');
  b.sayHello(); // hello jsong
  // age 11

  b.saySeeYou(); // see you
类还是原型关系

class没有实现类和对象的复制关系,仍然是通过[[Prototype]]委托,所以就还会有对象的引用都是同一个对象的关系
class C的原型上的方法修改后,不论是就的对象c1还是新的对象c2 他们的方法都会发生变化,因为c1和c2都共同委托class C的原型。

  class C {
    sayHello() {
      console.log('hello world');
    }
  }

  var c1 = new C();
  c1.sayHello(); // hello world

  C.prototype.sayHello = function() {
    console.log('see you world');
  };

  var c2 = new C();
  c2.sayHello(); // see you world

  c1.sayHello(); // see you world
如何声明属性

class不允许声明属性,但是我们可以在class的protype对象上添加需要声明的属性

  class C {
    constructor() {
      C.prototype.count++;
      console.log(`hello ${this.count}`);
    }
  }

  C.prototype.count = 0;

  var c1 = new C(); // hello 1
  console.log(c1.count); // 1
  var c2 = new C(); // hello 2
  console.log(c1.count); // 2
  console.log(c2.count); // 2

发布了83 篇原创文章 · 获赞 21 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/JsongNeu/article/details/97169002
今日推荐