new.target
属性ES6之前的生成实例对象的传统方法是经过构造函数:html
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);
复制代码
上面这种写法与传统的面向对象语言(好比 C++ 和 Java)差别很大,因此ES6中引入了Class
关键字,能够用来定义类,可是其大部分功能均可以用ES5实现,其更像一个语法糖。新的Class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。编程
上面的例子用ES6改写成以下:bash
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
复制代码
ES5 的构造函数Point
,对应 ES6 的Point
类的构造方法。 ES6 的类,彻底能够看做构造函数的另外一种写法:函数
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
复制代码
上面代码说明,类的数据类型就是函数,类自己就指向构造函数。ui
使用的时候也是直接new
一下,和构造函数的用法彻底一致:this
class Bar {
doStuff() {
console.log('stuff');
}
}
var b = new Bar();
b.doStuff() // "stuff"
复制代码
构造函数的prototype
属性,在 ES6 的“类”上面继续存在。事实上,类的全部方法都定义在类的prototype
属性上面:spa
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
复制代码
在类的实例上面调用方法,其实就是调用原型上的方法:prototype
class B {}
let b = new B();
b.constructor === B.prototype.constructor // true
复制代码
因为类的方法都定义在prototype
对象上面,因此类的新方法能够添加在prototype
对象上面。Object.assign
方法能够很方便地一次向类添加多个方法:3d
class Point {
constructor(){
// ...
}
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});
复制代码
prototype
对象的constructor
属性,直接指向“类”的自己,这与 ES5 的行为是一致的。code
Point.prototype.constructor === Point // true
复制代码
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
复制代码
var Point = function (x, y) {
// ...
};
Point.prototype.toString = function() {
// ...
};
Object.keys(Point.prototype)
// ["toString"]
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
复制代码
constructor
方法是类的默认方法,经过new
命令生成对象实例时,自动调用该方法。一个类必须有constructor
方法,若是没有显式定义,一个空的constructor方法会被自动添加:
class Point {
}
// 等同于
class Point {
constructor() {}
}
复制代码
constructor
方法默认返回实例对象(即this),彻底能够指定返回另一个对象:
class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo
// false
复制代码
上面代码中,constructor
函数返回一个全新的对象,结果致使实例对象不是Foo
类的实例。
类必须使用new
调用,不然会报错。这是它跟普通构造函数的一个主要区别,后者不用new
也能够执行:
class Foo {
constructor() {
return Object.create(null);
}
}
Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'
复制代码
必须使用new
实例化:
class Point {
// ...
}
// 报错
var point = Point(2, 3);
// 正确
var point = new Point(2, 3);
复制代码
与 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
复制代码
与 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__
属性为“类”添加方法。
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__.printName = function () { return 'Oops' };
p1.printName() // "Oops"
p2.printName() // "Oops"
var p3 = new Point(4,2);
p3.printName() // "Oops"
复制代码
使用实例的__proto__
属性改写原型,必须至关谨慎,不推荐使用,由于这会改变“类”的原始定义,影响到全部实例。
与 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
对象上的:
class CustomHTMLElement {
constructor(element) {
this.element = element;
}
get html() {
return this.element.innerHTML;
}
set html(value) {
this.element.innerHTML = value;
}
}
var descriptor = Object.getOwnPropertyDescriptor(
CustomHTMLElement.prototype, "html"
);
"get" in descriptor // true
"set" in descriptor // true
复制代码
类的属性名,能够采用表达式:
let methodName = 'getArea';
class Square {
constructor(length) {
// ...
}
[methodName]() {
// ...
}
}
复制代码
与函数同样,类也可使用表达式的形式定义:
const MyClass = class Me {
getClassName() {
return Me.name;
}
};
复制代码
须要注意的是,这个类的名字是Me
,可是Me
只在Class
的内部可用,指代当前类。在 Class
外部,这个类只能用MyClass
引用:
let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined
复制代码
若是类的内部没用到的话,能够省略Me
,也就是能够写成下面的形式:
const MyClass = class { /* ... */ };
复制代码
采用 Class 表达式,能够写出当即执行的 Class:
let person = new class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('张三');
person.sayName(); // "张三"
复制代码
1. 严格模式 类和模块的内部,默认就是严格模式,因此不须要使用use strict指定运行模式,ES6 实际上把整个语言升级到了严格模式。 2. 不存在变量提高 与ES5不一样,类不存在变量提高(hoist):
new Foo(); // ReferenceError
class Foo {}
复制代码
上面代码中,Foo
类使用在前,定义在后,这样会报错,由于 ES6 不会把类的声明提高到代码头部。
{
let Foo = class {};
class Bar extends Foo {
}
}
复制代码
上面的代码不会报错,由于Bar
继承Foo
的时候,Foo
已经有定义了。可是,若是存在class
的提高,上面代码就会报错,由于class
会被提高到代码头部,而let
命令是不提高的,因此致使Bar
继承Foo
的时候,Foo
尚未定义。
因为本质上,ES6 的类只是 ES5 的构造函数的一层包装,因此函数的许多特性都被Class继承,包括name属性:
class Point {}
Point.name // "Point"
复制代码
name
属性老是返回紧跟在class
关键字后面的类名。
若是某个方法以前加上星号(*),就表示该方法是一个 Generator
函数:
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world
复制代码
上面代码中,Foo
类的Symbol.iterator
方法前有一个星号,表示该方法是一个 Generator
函数。Symbol.iterator
方法返回一个Foo
类的默认遍历器,for...of
循环会自动调用这个遍历器。
类的方法内部若是含有this
,默认指向类的实例。
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
复制代码
上面代码中,printName
方法中的this
,默认指向Logger
类的实例。可是,若是将这个方法提取出来单独使用,this
会指向该方法运行时所在的环境(因为 class
内部是严格模式,因此 this
实际指向的是undefined
),从而致使找不到print
方法而报错。 能够在构造方法中绑定this
来解决:
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
复制代码
还可使用箭头函数来解决:
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
复制代码
箭头函数内部的this
老是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。 还有一种是使用proxy
,在获取方法的时候,自动绑定this
:
function selfish (target) {
const cache = new WeakMap();
const handler = {
get (target, key) {
const value = Reflect.get(target, key);
if (typeof value !== 'function') {
return value;
}
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
}
};
const proxy = new Proxy(target, handler);
return proxy;
}
const logger = selfish(new Logger());
复制代码
类至关于实例的原型,全部在类中定义的方法,都会被实例继承。若是在一个方法前,加上static
关键字,就表示该方法不会被实例继承,而是直接经过类来调用,这就称为“静态方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
复制代码
静态方法只能在类上面调用,而不能在实例上调用。
若是静态方法包含this
关键字,这个this
指的是类,而不是实例:
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello
复制代码
从上面能够看出静态方法能够与非静态方法重名。
父类的静态方法,能够被子类继承:
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'
复制代码
静态方法也是能够从super
对象上调用:
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod() // "hello, too"
复制代码
定义在constructor
里:
class IncreasingCounter {
constructor() {
this._count = 0;
}
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
复制代码
定义在顶部:
class IncreasingCounter {
_count = 0;
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
复制代码
class foo {
bar = 'hello';
baz = 'world';
constructor() {
// ...
}
}
复制代码
优势是不须要写this
,简单明了,一目了然。
class Foo {
}
Foo.prop = 1;
Foo.prop // 1
复制代码
上面的写法为Foo
类定义了一个静态属性prop
。
class MyClass {
static myStaticProp = 42;
constructor() {
console.log(MyClass.myStaticProp); // 42
}
}
复制代码
// 老写法
class Foo {
// ...
}
Foo.prop = 1;
// 新写法
class Foo {
static prop = 1;
}
复制代码
ES6 不提供私有方法和私有属性,只能经过变通方法模拟实现,一种作法是在命名上加以区别。
class Widget {
// 公有方法
foo (baz) {
this._bar(baz);
}
// 私有方法
_bar(baz) {
return this.snaf = baz;
}
// ...
}
复制代码
另外一种方法就是索性将私有方法移出模块,由于模块内部的全部方法都是对外可见的。
class Widget {
foo (baz) {
bar.call(this, baz);
}
// ...
}
function bar(baz) {
return this.snaf = baz;
}
复制代码
还有一种方法是利用Symbol值的惟一性,将私有方法的名字命名为一个Symbol值。
const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class myClass{
// 公有方法
foo(baz) {
this[bar](baz);
}
// 私有方法
[bar](baz) {
return this[snaf] = baz;
}
// ...
};
复制代码
上面代码中,bar
和snaf
都是Symbo
l值,通常状况下没法获取到它们,所以达到了私有方法和私有属性的效果。可是也不是绝对不行,Reflect.ownKeys()
依然能够拿到它们。
const inst = new myClass();
Reflect.ownKeys(myClass.prototype)
// [ 'constructor', 'foo', Symbol(bar) ]
复制代码
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 命令生成实例');
}
}
复制代码
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) {
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
会报错。