首页 > 编程语言 > 详细

JavaScript 原型es6写法

时间:2018-06-13 20:03:49      阅读:182      评论:0      收藏:0      [点我收藏+]

class Point{

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

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

}

定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错,类的方法都是写入在phototype中的,
class Bar {
  doStuff() {
    console.log(‘stuff‘);
  }
}

var b = new Bar();
b.doStuff() // "stuff" 调用类的方法,也是直接对类使用new命令,跟构造函数的用法完全一致。




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

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

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

Object.assign方法可以很方便地一次向类添加多个方法。

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

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

JavaScript 原型es6写法

原文:https://www.cnblogs.com/sunzhnan/p/9179494.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!