ES6-和与java有点儿相似的Class类

(该文章仅用于笔者的学习笔记,详情请阅读参考文献更好)
参考文献(阮一峰):https://es6.ruanyifeng.com/#docs/class

  JavaScript 语言中,生成实例对象的传统方法是通过构造函数

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

var p = new Point(1, 2);

  ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过 class 关键字,可以定义类。
  基本上,ES6 的class绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的class改写,就是下面这样。

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
  • 定义了一个“类”
  • constructor 方法,这就是构造方法
  • this 关键字则代表实例对象
  • ES5 的构造函数 Point ,对应 ES6 的Point类的构造方法
  • Point类除了构造方法,还定义了一个 toString 方法(不需要加上function)
  • 方法之间不需要逗号分隔,加了会报错

  类的数据类型就是函数,类本身就指向构造函数。(ES6 的类,完全可以看作构造函数的另一种写法。)

class Point {
  // ...
}

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

  使用的时候,也是直接对类使用 new 命令,跟构造函数的用法完全一致。

var b = new Bar();
b.doStuff() 

  构造函数的prototype属性,在 ES6 的“类”上面继续存在。
  事实上, 类的所有方法 都定义在类的 prototype 属性上面。

class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

  在类的实例上面调用方法,其实就是调用原型上的方法。

b.constructor === B.prototype.constructor // true

  由于类的方法都定义在 prototype 对象上面,所以类的新方法可以添加在 prototype 对象上面。 Object.assign 方法可以很方便地一次向类添加多个方法。

class Point {
  constructor(){
    // ...
  }
}

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

  类的内部所有定义的方法,都是 不可枚举的(non-enumerable).
  这一点与 ES5 的行为不一致。

//ES6
class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }
}
Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]


//ES5
var Point = function (x, y) {
  // ...
};

Point.prototype.toString = function() {
  // ...
};
Object.keys(Point.prototype)
// ["toString"]
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

上面代码中,
  采用 ES6 的写法,toString方法是Point类内部定义的方法,它是不可枚举的。
  采用 ES5 的写法,toString方法就是可枚举的。

实例属性的新写法

  实例属性除了定义在constructor()方法里面的this上面,也 可以定义在类的最顶层

class foo {
  bar = 'hello';
  baz = 'world';

  constructor() {
    // ...
  }
}

  这种新写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。

constructor 方法

  • constructor 方法是类的默认方法,通过new命令生成对象实例时,
  • 自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被 默认添加
  • 类必须使用 new 调用,否则会报错。(这是它跟普通构造函数的一个主要区别)

  constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

class Foo {
  constructor() {
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false

  上面代码中,constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

类的实例

  生成类的实例的写法,与 ES5 完全一样,也是使用new命令。
  与 ES5 一样, 实例的属性 除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。

//定义类
class Point {

  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }

}

var point = new Point(2, 3);

point.toString() // (2, 3)

point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

上面代码中,
  x和y都是实例对象point自身的属性(因为定义在this变量上),所以hasOwnProperty方法返回true
  而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法返回false。这些都与 ES5 的行为保持一致。

  与 ES5 一样,类的所有实例共享一个原型对象。

var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__ === p2.__proto__
//true

上面代码中,
  p1和p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

  这也意味着,可以通过实例的__proto__属性为“类”添加方法。(不推荐使用)
  生产环境中,我们可以使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性。

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

  与 ES5 一样,在“类”的内部可以使用get和set关键字——对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: '+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

  存值函数和取值函数是设置在属性的 Descriptor 对象上的。

属性表达式

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

let methodName = 'getArea';

class Square {
  constructor(length) {
    // ...
  }

  [methodName]() {
    // ...
  }
}

上面代码中,
  Square类的方法名getArea,是从表达式得到的。

Class表达式

const MyClass = class Me {
  getClassName() {
    return Me.name;
  }
};

let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined


//如果类的内部没用到的话,可以省略Me
const MyClass = class { /* ... */ };
  • 这个类的名字是Me,但是Me只在 Class 的 内部可用 ,指代当前类。
  • 在 Class 外部,这个类只能用MyClass引用。
  • 如果类的内部没用到的话,可以 省略Me
  • 采用 Class 表达式,可以写出 立即执行的 Class。
let person = new class {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(this.name);
  }
}('张三');

person.sayName(); // "张三"

  person是一个立即执行的类的实例。

注意点

  • 严格模式
  • 不存在提升
  • name 属性
  • Generator 方法
  • this 的指向

静态方法

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

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

  上面代码中,Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

  注意,如果静态方法包含this关键字,这个this指的是 ,而不是实例。

class Foo {
  static bar() {
    this.baz();
  }
  static baz() {
    console.log('hello');
  }
  baz() {
    console.log('world');
  }
}

Foo.bar() // hello

上面代码中,
  静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。
  另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

  父类的静态方法,可以被子类继承。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
}

Bar.classMethod() // 'hello'

上面代码中,
  父类Foo有一个静态方法,子类Bar可以调用这个方法。

  静态方法也是可以从super 对象上调用的。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}

Bar.classMethod() // "hello, too"

静态属性

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

class Foo {
}

Foo.prop = 1;
Foo.prop // 1

私有方法和私有属性

  私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但 ES6 不提供,只能通过变通方法模拟实现。

new.target 属性

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


  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值