javascript笔记之ES6的Class基本语法

因为ES6里面的class实现是基本上是es5时代实现方式的语法糖,没有es5的直接,也没有像java等面向对象编程语言的纯粹。

class Point {
  // 私有属性和私有方法已经被支持,使用的是以 # 符号来标示的
  // 如果在类外使用 #count, 会收获一个错误  Private field '#count' must be declared in an enclosing class
  #count=0;
  // 私有方法的支持还是实现性质,并没有加入标准
  //#sum(b) {
  //  return #count + b;
  //}
  // 定义实例属性的语法糖,效果和下面定义x、y效果是一样的,都是挂载在 this 上
  color="red";
  // constructor是构造方法,this 代表实例对象
  // constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。
  // 如果没有显式定义,一个空的constructor方法会被默认添加。
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  // 实例方法
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
  staff(){
  	console.log("staff");
  }
  // 通过 static 关键字修饰,表示该方法是静态方法,直接通过类来调用,不可枚举
  // 注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
  static classMethod() {
    return 'hello';
  }
}

es6有明确的class语法糖,比之前使用hack的办法去实现class明确清晰,更像面向对象编程的语法了。但是新的写法内部的实现依然是基于对象原型的,和ES5并没有本质上的区别。

// 本质上仍然是函数
typeof Point; // "function"
// 和 es5 一样,prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。
Point === Point.prototype.constructor; // true
// 实例方法依然定义在prototype上面。
console.log(Point.prototype);  // {constructor: ƒ, toString: ƒ, staff: ƒ}

let point = new Point();
// point对象的constructor方法就是Point类原型的constructor方法,没有变化
console.log(point.constructor === Point.prototype.constructor);

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

在使用上,类和普通构造函数还是有些区别的。

  • 类必须使用new调用,使用applycall等方式调用会直接报错。这是它跟普通构造函数的一个主要区别
    Point() // TypeError: Class constructor Foo cannot be invoked without 'new'
    Point.call() // TypeError: Class constructor Foo cannot be invoked without 'new'
    
  • Point类内部定义的方法,虽然也是在prototype上,但它是不可枚举的。这一点与 ES5 的行为不一致。
    function Point2(x, y) {
      this.x = x;
      this.y = y;
      this.color = "red";
    }
    
    Point2.prototype.toString = function() {
      return "(" + this.x + ", " + this.y + ")";
    };
    Object.keys(Point.prototype) // []
    Object.keys(Point2.prototype) // ["toString"]
    
  • 类不存在变量提升(hoist),这一点与 ES5 完全不同。
    new Foo(); // ReferenceError
    class Foo {}
    

new.target 属性

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

function Person(name) {
  if (new.target !== undefined) {
    this.name = name;
  } else {
    throw new Error('必须使用 new 命令生成实例');
  }
}

// 另一种写法
function Person(name) {
  if (new.target === Person) {
    this.name = name;
  } else {
    throw new Error('必须使用 new 命令生成实例');
  }
}

var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三');  // 报错

上面代码确保构造函数只能通过new命令调用。

Class 内部调用new.target,返回当前 Class。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle);
    this.length = length;
    this.width = width;
  }
}

var obj = new Rectangle(3, 4); // 输出 true

需要注意的是,子类继承父类时,new.target会返回子类。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle);
    // ...
  }
}

class Square extends Rectangle {
  constructor(length, width) {
    super(length, width);
  }
}

var obj = new Square(3); // 输出 false

上面代码中,new.target会返回子类。

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new Error('本类不能实例化');
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    super();
    // ...
  }
}

var x = new Shape();  // 报错
var y = new Rectangle(3, 4);  // 正确

上面代码中,Shape类不能被实例化,只能用于继承。

注意,在函数外部,使用new.target会报错。

参考

http://es6.ruanyifeng.com/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值