本文共 2705 字,大约阅读时间需要 9 分钟。
ES6之前,我们都是通过构造函数来生成实例对象:
function Point (x,y){ this.x = x this.y = y}Point.prototype.sum = function(){ return this.x + this.y}let point = new Point(1,2)console.log(point.sum()) // 3
ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。基本语法:
class Point{ constructor(x,y){ this.x = x this.y = y } sum(){ return this.x + this.y } } let point = new Point(1,2) console.log(point.sum()) // 3
注意:
new
命令,跟构造函数的用法完全一致。class Point { constructor() { // ... } toString() { // ... } toValue() { // ... }}// 等同于Point.prototype = { constructor() { }, toString() { }, toValue() { },};// Object.assign方法可以很方便地一次向类添加多个方法。Object.assign(Point.prototype, { toString(){ }, toValue(){ }});
class Point { }// 等同于class Point { constructor() { }}
var p1 = new Point(2,3);var p2 = new Point(3,2);p1.__proto__ === p2.__proto__//true
let methodName = 'getArea';class Square { constructor(length) { // ... } [methodName]() { // ... }}
const MyClass = class Me { getClassName() { return Me.name; }};let inst = new MyClass();inst.getClassName() // MeMe.name // ReferenceError: Me is not defined
class Foo { static classMethod() { return 'hello'; }}Foo.classMethod() // 'hello'var foo = new Foo();foo.classMethod()// TypeError: foo.classMethod is not a function
class IncreasingCounter { _count = 0; get value() { console.log('Getting the current value!'); return this._count; } increment() { this._count++; }}
class MyClass { static myStaticProp = 42; constructor() { console.log(MyClass.myStaticProp); // 42 }}
function Person(name) { if (new.target !== undefined) { this.name = name; } else { throw new Error('必须使用 new 命令生成实例'); }}
转载地址:http://ztri.baihongyu.com/