ES6-Class

Class

第一次接触的你需要注意哪些地方

  • 类结构体内部的方法定义不能(不需要)使用function字段
  • 类名必须大写。好像没有明确规定,但你就当有这个规定吧
  • 类结构体虽然是放在{}内,但此时的{}并不表示对象,而表示代码块,所以不要像之前定义prototype一样使用,分割各个函数
  • 类结构体中的所有方法都会被挂载到prototype对象上,成为各实例的通用方法
  • 同let&const一样,不存在变量提升
  • 不多说,都在demo里了,走一个。。。
new Demo() // 不存在变量提升,这里会报错

class Demo { // 类名大写
  constructor(x, y) { // 构造函数。可以不定义构造函数默认`constructor() {}`
    this.x = x;
    this.y = y;
  } // 不需要`,`分割
  toString() { // 不需要`function`定义函数
    return '(' + this.x + ', ' + this.y + ')';
  }
}

继承 extends

  • 子类通过构造函数向父类传参
  • super代表父类的构造函数
  • 调用super之后才能使用this关键字,否则会报错
  • demo
class DemoChild extends Demo{
    constructor(...args){
        this.args = args; // 报错啦,这里还没有this呢。。
        super(...args);
        this.args = args; //这才对嘛。。
    }
}
  • 可以继承原生构造函数
class GoodArray extends Array{ // 妈妈再也不用担心对原生构造函数的扩展带来的各种问题
    constructor(...args){
        super(...args);
    }
    toString(){
        console.log('I am better then Array');
    }
}
var arr = new GoodArray();
arr.toString();

prototype & __proto__

  • __proto__总是指向父类
  • prototype的__proto__总是指向父类的prototype
  • 绕死算了v
    DemoChild.\_\_proto\_\_ === Demo;
    DemoChild.prototype.\_\_proto\_\_ === Demo.prototype;

getter & setter

  • class内部可以定义get&set方法,用于存取属性的值。用法和对象属性的getter&setter相同
class Demo{
    constructor(foo){
        this._foo = foo;
    }
    get foo(){
        console.log('get foo: ' + this._foo);
        return this._foo;
    }
    set foo(val){
        this._foo = val;
        console.log('set foo: ' + this._foo);
    }
}
var demo = new Demo(111);
demo.foo = 123; // set foo: 123
demo.foo; // get foo: 123

静态方法

  • static关键字
  • 静态方法可以直接通过类名调用,不需要实例化
  • 静态方法不会被实例继承
  • 父类的静态方法可以被子类继承
  • 静态方法也可以通过supper()调用
  • 来个糖炒栗子吧
class Demo{
    static hello(){
        console.log('hello');
    }
}
class ChildDemo extends Demo{
}
var demo = new Demo();
var childDemo = new ChildDemo();
Demo.hello(); // hello
ChildDemo.hello(); // hello
demo.hello(); // 报错啦
childDemo.hello(); // 根本就没执行到我,其实我也一样报错

静态属性和实例属性

  • 如何定义静态属性?ES6规定Class内部只允许定义静态方法,不允许定义静态属性,ES7中有内部定义静态属性的提案,但是那是ES7的事情了
  • 实例属性只能在constructor中定义
class Demo{
    constructor(...props){
        this.props = props; // 定义实例属性
    }
}
Demo.props = 'static props';
var demo = new Demo(1, 2, 3);
console.log(demo.props); // [1, 2, 3]
console.log(Demo.props); // 'static props'
posted @ 2016-06-23 10:17  DDFE  阅读(288)  评论(0编辑  收藏  举报