你不知道的JavaScript编程语言爱好者让前端飞

读Javascript最佳实践(8)-ES6类及类属性

2019-07-05  本文已影响15人  全栈顾问

翻译自《javascript-best-practice》

ES6为JavaScript引入了类,但它们对于复杂的应用程序来说太简单了。Class Fields(也称为类属性)旨在提供具有私有和静态成员的更简单的构造函数。该提案目前处于TC39第3阶段:候选人,可能出现在ES2019(ES10)中。

在我们更详细地检查类字段之前,快速回顾一下ES6类是很有用的。

ES6类基础知识

JavaScript的原型继承模型可能会让开发人员感到困惑,因为他们了解C ++,C#,Java和PHP等语言中使用的经典继承。JavaScript类主要是语法糖,但它们提供了更熟悉的面向对象编程概念。

类是一个模板,用于定义该类型的对象的行为方式。下面的Animal类定义了通用动物(类通常用首字母大写表示,以区别于对象和其他类型):

class Animal {

  constructor(name = 'anonymous', legs = 4, noise = 'nothing') {

    this.type = 'animal';
    this.name = name;
    this.legs = legs;
    this.noise = noise;

  }

  speak() {
    console.log(`${this.name} says "${this.noise}"`);
  }

  walk() {
    console.log(`${this.name} walks on ${this.legs} legs`);
  }

}

类声明以严格模式执行;没有必要添加'use strict'。

创建此类型的对象时运行constructor方法,并且通常在其中定义初始属性。speak()并且walk()是添加其他功能的方法。

现在可以使用new关键字从此类创建对象:

const rex = new Animal('Rex', 4, 'woof');
rex.speak();          // Rex says "woof"
rex.noise = 'growl';
rex.speak();          // Rex says "growl"

Getter和Setter

Setter是用于仅定义值的特殊方法。同样,Getters是用于仅返回值的特殊方法。例如:

class Animal {
constructor(name = 'anonymous', legs = 4, noise = 'nothing') {

    this.type = 'animal';
    this.name = name;
    this.legs = legs;
    this.noise = noise;

  }

  speak() {
    console.log(`${this.name} says "${this.noise}"`);
  }

  walk() {
    console.log(`${this.name} walks on ${this.legs} legs`);
  }

  // setter
  set eats(food) {
    this.food = food;
  }

  // getter
  get dinner() {
    return `${this.name} eats ${this.food || 'nothing'} for dinner.`;
  }
}

const rex = new Animal('Rex', 4, 'woof');
rex.eats = 'anything';
console.log( rex.dinner );  // Rex eats anything for dinner.

MDN setter The set syntax binds an object property to a function to be called when there is an attempt to set that property.
MDN getter The get syntax binds an object property to a function that will be called when that property is looked up.

子对象或子类

使用一个类作为另一个类的基础通常是实用的。如果我们主要创建狗对象,那就Animal太通用了,我们必须每次都指定相同属性值的4(legs)和“woof”(noise)。

Dog类可以使用extends从Animal类继承所有属性和方法。可以根据需要添加或删除特定于狗的属性和方法:

class Dog extends Animal {

  constructor(name) {

    // call the Animal constructor
    super(name, 4, 'woof');
    this.type = 'dog';

  }

  // override Animal.speak
  speak(to) {

    super.speak();
    if (to) console.log(`to ${to}`);

  }

}

super指的是父类,通常在constructor中调用。在此示例中,Dog speak()方法会覆盖在Animal类中定义的方法。

Dog现在可以创建对象实例:

const rex = new Dog('Rex');
rex.speak('everyone');      // Rex says "woof" to everyone

rex.eats = 'anything';
console.log( rex.dinner );  // Rex eats anything for dinner.

静态方法和属性

使用static关键字定义方法允许在类上调用它而不创建对象实例。JavaScript不像其他语言那样支持静态属性,但可以向类定义添加属性(a class本身就是一个JavaScript对象!)。

该Dog级可适应保留多少狗对象已经创建了一个数:

class Dog extends Animal {

  constructor(name) {

    // call the Animal constructor
    super(name, 4, 'woof');
    this.type = 'dog';

    // update count of Dog objects
    Dog.count++;

  }

  // override Animal.speak
  speak(to) {

    super.speak();
    if (to) console.log(`to ${to}`);

  }

  // return number of dog objects
  static get COUNT() {
    return Dog.count;
  }

}

// static property (added after class is defined)
Dog.count = 0;

类的静态属性的COUNT的getter返回创建的狗的数量:

console.log(`Dogs defined: ${Dog.COUNT}`); // Dogs defined: 0

const don = new Dog('Don');

console.log(`Dogs defined: ${Dog.COUNT}`); // Dogs defined: 1

const kim = new Dog('Kim');

console.log(`Dogs defined: ${Dog.COUNT}`); // Dogs defined: 2

有关更多信息,请参阅面向对象的JavaScript:深入了解ES6类

ESnext类字段

类字段(class field)提议允许在类的顶部初始化属性:

class MyClass {

  a = 1;
  b = 2;
  c = 3;

}

这相当于:

class MyClass {

  constructor() {
    this.a = 1;
    this.b = 2;
    this.c = 3;
  }

}

初始化程序在任何构造函数运行之前执行(假设仍然需要构造函数)。

静态类字段

类字段允许在类中声明静态属性。例如:

class MyClass {

  x = 1;
  y = 2;
  static z = 3;

}

console.log( MyClass.z ); // 3

不雅的ES6等价物:

class MyClass {

  constructor() {
    this.x = 1;
    this.y = 2;
  }

}

MyClass.z = 3;

console.log( MyClass.z ); // 3

私有类字段

ES6类中的所有属性默认都是公共的,可以在类外检查或修改。在Animal上面的示例中,无法阻止直接修改food,而不是通过调用eats的setter:

class Animal {
constructor(name = 'anonymous', legs = 4, noise = 'nothing') {

    this.type = 'animal';
    this.name = name;
    this.legs = legs;
    this.noise = noise;

  }

  set eats(food) {
    this.food = food;
  }

  get dinner() {
    return `${this.name} eats ${this.food || 'nothing'} for dinner.`;
  }

}

const rex = new Animal('Rex', 4, 'woof');
rex.eats = 'anything';      // standard setter
rex.food = 'tofu';          // bypass the eats setter altogether
console.log( rex.dinner );  // Rex eats tofu for dinner.

其他语言允许private声明属性。这在ES6中是不可能的,尽管开发人员可以使用下划线约定(_propertyName)来解决它。

在ESnext中,使用哈希#前缀定义私有类字段:

class MyClass {

  a = 1;          // .a is public
  #b = 2;         // .#b is private
  static #c = 3;  // .#c is private and static

  incB() {
    this.#b++;
  }

}

const m = new MyClass();

m.incB(); // runs OK
m.#b = 0; // error - private property cannot be modified outside class

请注意,虽然TC39第2阶段:提案草案建议#在名称上使用哈希前缀,但无法定义私有方法,getter和setter 。例如:

class MyClass {

  // private property
  #x = 0;

  // private method (can only be called within the class)
  #incX() {
    this.#x++;
  }

  // private setter (can only be called within the class)
  set #setX(x) {
    this.#x = x;
  }

  // private getter (can only be called within the class)
  get #getX() {
    return this.$x;
  }

}

直接受益:更清洁的反应代码!

React组件通常具有与DOM事件关联的方法。为了确保this解析组件,相应的bind每个方法都是必要的。例如:

class App extends Component {

  constructor() {

    super();

    state = { count: 0 };

    // bind all methods
    this.incCount = this.incCount.bind(this);
  }

  incCount() {
    this.setState(ps => ({ count: ps.count + 1 }));
  }

  render() {

    return (
      <div>
        <p>{ this.state.count }</p>
        <button onClick={this.incCount}>add one</button>
      </div>
    );

  }
}

如果incCount定义为类字段,则可以使用ES6 =>将其设置为函数,该箭头会自动将其绑定到定义对象。该state还可以声明为类字段,因此没有构造是必需的:

class App extends Component {

  state = { count: 0 };

  incCount = () => {
    this.setState(ps => ({ count: ps.count + 1 }));
  };

  render() {

    return (
      <div>
        <p>{ this.state.count }</p>
        <button onClick={this.incCount}>add one</button>
      </div>
    );

  }
}

今天使用类字段

浏览器或Node.js当前不支持类字段。但是,可以使用Babel转换语法,Babel在使用Create React App时默认启用。或者,可以使用以下终端命令安装和配置Babel:

mkdir class-properties
cd class-properties
npm init -y
npm install --save-dev babel-cli babel-plugin-transform-class-properties
echo '{ "plugins": ["transform-class-properties"] }' > .babelrc

build在以下scripts部分添加命令package.json:

"scripts": {
  "build": "babel in.js -o out.js"
},

然后运行npm run build以将ESnext文件in.js转换为跨浏览器兼容的文件out.js

已经提出了 Babel对私有方法,getter和setter的支持。

类字段:是一种改进?

ES6类定义过于简单化。类字段应该有助于提高可读性并启用一些有趣的选项。我并不特别喜欢使用哈希#来表示私有成员,但是如果没有它就会产生意外的行为和性能问题(有关详细说明,请参阅JavaScript的新#private类字段)。

也许这是不言而喻的,但无论如何我都会说:本文中讨论的概念可能会有所变化,可能永远不会实现!也就是说,JavaScript类字段具有实际的好处,并且兴趣正在上升。这是一个安全的赌注。

上一篇下一篇

猜你喜欢

热点阅读