类和继承

生成实例对象的传统方法是通过构造函数

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function () {
  console.log(  `hello, ${this.name}, i am ${this.age} years old`);
};

var p = new Person('hunger', 2);

ES6 的class造函数

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log( `hello, ${this.name}, i am ${this.age} years old`);
  }
}

静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class EventCenter {
  static fire() {
    return 'fire';
  }
  static on(){
    return 'on'
  }
}

等同于

function EventCenter(){
}
EventCenter.fire = function(){}
EventCenter.on = function(){}

类必须使用new调用,否则会报错。

这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。

class Foo {
  constructor() {
    return Object.create(null);
  }
}

Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'

类不存在变量提升(hoist)

{
  let Foo = class {};
  class Bar extends Foo {
  }
}

私有方法和私有属性

私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现

  • 就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。
class Widget {
  foo (baz) {
    bar.call(this, baz);
  }

  // ...
}

function bar(baz) {
  return this.snaf = baz;
}
  • 利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。
onst bar = Symbol('bar');
const snaf = Symbol('snaf');

export default class myClass{

  // 公有方法
  foo(baz) {
    this[bar](baz);
  }

  // 私有方法
  [bar](baz) {
    return this[snaf] = baz;
  }

  // ...
};

Class 的继承

class Person{
    constructor(name){
        this.name = name;
    }
    sayname(){
        console.log(this.name);
    }
};
class Stundent extends Person{
  constructor(name,score){
    super(name);
    this.score=score;
  }
  sayscore(){
    console.log(this.score);
  }
}
let s1 =new Stundent("xiahui","90");

Object.getPrototypeOf方法

可以使用这个方法判断,一个类是否继承了另一个类

Object.getPrototypeOf(Stundent) === Person
// true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容