class

1.语法

  //定义类
     class Point {
        constructor(x, y) {
          this.x = x;
          this.y = y;
        }

       toString() {
          return '(' + this.x + ', ' + this.y + ')';
       }
   }
  • 定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。
    类的所有方法都定义在类的prototype属性上面

  • 类本身就指向构造函数。prototype对象的constructor属性,直接指向“类”的本身

         Point === Point.prototype.constructor // true
    
  • b是B类的实例,它的constructor方法就是B类原型的constructor方法

       b.constructor === B.prototype.constructor // true
    
  • 类的内部所有定义的方法,都是不可枚举的(non-enumerable)
    ** hasOwnProperty()**返回false。只有在对象本身的属性成员才会返回true。比如构造函数constructor中的this.x, this.y。

         hasOwnproperty(x)//true;
    

用** Object.getPrototypeOf()** 方法来获取实例对象的原型.

  • class表达式

         const MyClass = class { /* ... */ };
         //立即执行的class
       let person = new class {
           constructor(name) {
              this.name = name;
            }
    
           sayName() {
             console.log(this.name);
            }
       }('张三');
    
       person.sayName(); // "张三"
    

2.不存在变量提升

  函数调用要在定义的后面

3.私有方法

  • 只在命名上进行区分(私有函数名前有_)

  • 私有函数单拎出来,class内使用call方法调用

  • 利用Symbol值的唯一性定义函数名

      const bar = Symbol('bar');
      const snaf = Symbol('snaf');
    
      export default class myClass{
    
       // 公有方法
      foo(baz) {
        this[bar](baz);
      }
    
       // 私有方法
     [bar](baz) {
        return this[snaf] = baz;
      }
    
     // ...
    };
    

4.私有属性#X

5.this的指向

对象方法中的this指向引用方法的对象。如果对象中的方法被单独拎出来调用,则this指向执行环境。为了解决这个问题,要将方法中的this进行绑定

  • 使用箭头函数

  • 在constructor中

          this.fun = this.fun.bind(this)
    

6.class中的generator函数

    class Foo {
      constructor(...args) {
      this.args = args;
    }
   * [Symbol.iterator]() {
      for (let arg of this.args) {
         yield arg;
      }
   }
 }

 for (let x of new Foo('hello', 'world')) {
    console.log(x);
 }
// hello
// world

Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。

7.class中的静态方法

方法前加关键字static。
类的静态方法不会被实例所继承。
父类的静态方法可以被子类所继承

8.new.target

  • 当new命令作用于构造函数,则newnew.target返回作用的构造函数,否则返回undefined。new.target确保构造函数只能够被new 调用。
  • 当子类继承父类,new.target 返回的是子类。可利用这一点实现不能够实例化的类

9.

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

推荐阅读更多精彩内容