class 类

作者: Sccong | 来源:发表于2017-07-10 23:00 被阅读0次

es6 新加了class类,类实际上是个“特殊的函数”,就像你能够定义的函数表达式和函数声明一样,使用方法类似这样

class a{
    constructor(props){//如果是父类,不用写super
        super(props)
    }
    xxxx
}
  • 先说下super是做什么的,简单来说,就是有三种用法(一般都是第一种)。
  • 第一种
//super(props)
class sn{
      r(){
          alert(2)
    }
};
class  a extends sn{
      constructor(props){
            super(props);
            this.r()
      }
}
var s=new a();//结果是alert(2)
  • 第二种
//super()作为对象调用,指代父类
class sn{
      r(){
            alert(2)
      }
};
class  a extends sn{
      constructor(){
            super();
            super.r()
      }
}
var s=new a();//结果是alert(2)
  • 第三种
//super()作为函数调用,指代父类(sn)的构造函数
class sn{
      constructor(){
        alert(2)
      }
};
class  a extends sn{
      constructor(){
            super()
      }
}
var s=new a();//结果是alert(2)
  • 函数声明和类声明之间的一个重要区别是函数声明会[声明提升],类声明不会。你首先需要声明你的类,然后访问它,否则会抛出一个[ReferenceError]。

  • 类声明 默认的函数都是在prototype上面.

class Scc {}
class a extends Scc {
    constructor(props){
        super(props);
        this.sss=2
    }
    b(){
        console.log('this is b')
    }
}
console.log(a.prototype)//Scc {constructor: function, b: function}
console.log(new a().sss)// 2
  • static 静态方法
    类声明里面的函数通过实例化之后 才能调用,除非用static 静态方法,可以直接调用。静态方法不能通过实例调用,而是直接通过类来调用
class Scc {
    static a(){
        console.log('this is static a')
    }
}
console.log(Scc.a()) // 输出 this is static a
  • 使用 extends 创建子类
class Animal { 
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}
class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}
var d = new Dog('Mitzie');
// 'Mitzie barks.'
d.speak();

如果子类中的constructor中有用到this,必须在此之前调用super()

相关文章

网友评论

      本文标题:class 类

      本文链接:https://www.haomeiwen.com/subject/joouhxtx.html