@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
更多
你可能也喜欢
- 2662419405sh 中文文档教程
- 8fold-web-assets 中文文档教程
- @010webdev/react-prerender 中文文档教程
- @10duke/event-data-reader-cli 中文文档教程
- @1flow-inc/react-native-1flow-sdk 中文文档教程
- @24hr/content-next 中文文档教程
- @47ng/check-env 中文文档教程
- @4qwerty7/sim-node 中文文档教程
- @4so-fourseasons/react-hoc-spinners 中文文档教程
- @7factor/react-native-form-builder 中文文档教程