@activeprospect/old 中文文档教程
old
使 ES6 类的 'new' 关键字可选
Usage
npm install old
var old = require('old')
class Class {
// ...
}
var Class2 = old(Class)
Class() // throws error
Class2() // creates an instance of Class
Rationale
对于 ES5“构造函数”函数,一个常见的模式是使 new
关键字可选,方法如下:
function Foo () {
if (!(this instanceof Foo)) return new Foo()
// do constructor stuff
}
最近,ES6 引入了类来替换构造函数。 但是,如果这些类是在没有 new
的情况下实例化的,则会抛出错误:TypeError: Class constructor Foo cannot be invoked without 'new'
。 这个模块使 new
成为可选的,即使对于这些 ES6 类也是如此。
Credit
- Thank you to Sorella in ##javascript (Freenode) for the clean solution
- Thanks to slikts in ##javascript for the name idea
old
Make the 'new' keyword optional for ES6 classes
Usage
npm install old
var old = require('old')
class Class {
// ...
}
var Class2 = old(Class)
Class() // throws error
Class2() // creates an instance of Class
Rationale
With ES5 "constructor" functions, a common pattern is to make the new
keyword optional by doing something like the following:
function Foo () {
if (!(this instanceof Foo)) return new Foo()
// do constructor stuff
}
Recently, ES6 introduced classes to replace constructor functions. However, if these classes are instantiated without new
, an error is thrown: TypeError: Class constructor Foo cannot be invoked without 'new'
. This module makes new
optional, even for these ES6 classes.
Credit
- Thank you to Sorella in ##javascript (Freenode) for the clean solution
- Thanks to slikts in ##javascript for the name idea