7.Class

作者: KeithFu | 来源:发表于2016-11-26 16:27 被阅读0次

引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

//定义类
class Point { 
   constructor(x, y) {
     this.x = x; this.y = y;
   }
//定义方法
   toString() { 
    return '(' + this.x + ', ' + this.y + ')';
   }
}

typeof Point // "function"
Point === Point.prototype.constructor // true

上面代码表明,类的数据类型就是函数,类本身就指向构造函数。类的所有方法都定义在类的prototype属性上面。

Object.assign(Point.prototype, { 
sayAge(){},
toValue(){}
});

类的属性名,可以采用表达式。

let methodName = "getArea";
class Square{ 
  constructor(length) {  // ... } 
  [methodName]() { 
  // ... }
}

constructor方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

class Foo { 
  constructor() {
     return Object.create(null); 
  }
}
new Foo() instanceof Foo // false

Class表达式

与函数一样,类也可以使用表达式的形式定义。

const MyClass = class Me { 
  getClassName() { 
//me仅用于内部调用使用,外部无效
    return Me.name; 
  }
};
//如果内部无须引用  Me,可简写
const MyClass = class {...}

采用Class表达式,可以写出立即执行的Class。

let person = new class { 
  constructor(name) {
     this.name = name;
   } 
  sayName() { 
    console.log(this.name);
   }
}('张三');
person.sayName(); // "张三"

this的指向

类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

class Logger { 
  printName(name = 'there') { this.print(`Hello ${name}`); } 
  print(text) { console.log(text); }
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined

上面代码中,printName方法中的this默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print
方法了。

class Logger {
   constructor() { this.printName = this.printName.bind(this); }  
// ...
}

另一种解决方法是使用箭头函数。

class Logger {
   constructor() {
     this.printName = (name = 'there') => { 
        this.print(`Hello ${name}`);
     }; 
  }  
// ...
}

还有一种解决方法是使用Proxy,获取方法的时候,自动绑定this

function selfish (target) {
   const cache = new WeakMap(); 
   const handler = { 
    get (target, key) { 
       const value = Reflect.get(target, key); 
      if (typeof value !== 'function') { return value; } 
      if (!cache.has(value)) { cache.set(value, value.bind(target)); } 
      return cache.get(value); 
    } 
  }; 
  const proxy = new Proxy(target, handler); 
  return proxy;
}
const logger = selfish(new Logger());

Class的继承

class ColorPoint extends Point { 
  constructor(x, y, color) { 
    super(x, y); // 调用父类的constructor(x, y) 
    this.color = color; 
  } 
  toString() {
     return this.color + ' ' + super.toString(); // 调用父类的toString()
   }
}

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
如果子类没有定义constructor方法,这个方法会被默认添加

Class的取值函数(getter)和存值函数(setter)

class CustomHTMLElement { 
  constructor(element) { this.element = element; } 
  get html() { return this.element.innerHTML; } 
  set html(value) { this.element.innerHTML = value; }
}
var descriptor = Object.getOwnPropertyDescriptor( CustomHTMLElement.prototype, "html");
"get" in descriptor  // true
"set" in descriptor  // true

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

上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个Generator函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。

Class的静态方法

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

class Foo { 
  static classMethod() { return 'hello'; }
}
var foo=new Foo()
foo.classMethod();// TypeError: foo.classMethod is not a function
class Bar extends Foo {}
Bar.classMethod(); 
// 'hello'

Class的静态属性和实例属性

静态属性指的是Class本身的属性,即Class.propname,而不是定义在实例对象(this)上的属性。

ES7有一个静态属性的[提案]properties),目前Babel转码器支持。

类的实例属性可以用等式,写入类的定义之中。

class MyClass { 
  myProp = 42; 
  constructor() { 
    console.log(this.myProp); 
    // 42
   }
}
class ReactCounter extends React.Component { state = { count: 0 };}
//对于已经在对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。
class ReactCounter extends React.Component { 
  constructor(props) { 
    super(props); 
    this.state = { 
      count: 0 
    }; 
  } 
  state;
}

类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了

class MyClass { 
  static myStaticProp = 42; 
  constructor() {
     console.log(MyClass.myProp);
     // 42
   }
}

new.target属性
new是从构造函数生成实例的命令。ES6为new命令引入了一个new.target属性,(在构造函数中)返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined因此这个属性可以用来确定构造函数是怎么调用的。

用处1:可以写出不能独立使用、必须继承后才能使用的类
用处2:确保构造函数只能通过new,不是通过call方式命令调用

Mixin模式的实现

Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。它在ES6的实现如下。

function mix(...mixins) {
 class Mix {} 
  for (let mixin of mixins) { 
    copyProperties(Mix, mixin); 
    copyProperties(Mix.prototype, mixin.prototype); } 
    return Mix;
  }
  function copyProperties(target, source) { 
    for (let key of Reflect.ownKeys(source)) { 
    if ( key !== "constructor" && key !== "prototype" && key !== "name" ) {
       let desc = Object.getOwnPropertyDescriptor(source, key);         
       Object.defineProperty(target, key, desc); 
  } 
 }
}

上面代码的mix
函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

class DistributedEdit extends mix(Loggable, Serializable) {  // ...}

相关文章

  • 7.Class

    引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。 上面代码表明,类的数据类型就是...

网友评论

      本文标题:7.Class

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