Skip to content

Commit a92fb2e

Browse files
committed
fix: support extending an ES2015 class
Only if `Reflect.construct` is available. Fixes #18
1 parent 9191125 commit a92fb2e

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
language: node_js
22
node_js:
33
- stable
4+
- 8
45
- 6
56
- 5
67
- 4

index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
// ===================================================================
66

7+
var construct = typeof Reflect !== 'undefined' ? Reflect.construct : undefined
78
var defineProperty = Object.defineProperty
89

910
// -------------------------------------------------------------------
@@ -102,7 +103,9 @@ function makeError (constructor, super_) {
102103
var name
103104
if (typeof constructor === 'string') {
104105
name = constructor
105-
constructor = function () { super_.apply(this, arguments) }
106+
constructor = construct !== undefined
107+
? function () { return construct(super_, arguments, constructor) }
108+
: function () { super_.apply(this, arguments) }
106109

107110
// If the name can be set, do it once and for all.
108111
if (setFunctionName !== undefined) {

index.spec.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,4 +169,20 @@ describe('BaseError', function () {
169169
expect(typeof e.stack).toBe('string')
170170
compareStacks(e.stack, stack)
171171
})
172+
173+
;(typeof Reflect !== 'undefined' ? it : it.skip)('can be reused as base error', function () {
174+
class MyBaseError extends BaseError {}
175+
var MyError = makeError('MyError', MyBaseError)
176+
177+
var e = new MyError('my error message'); var stack = new Error().stack
178+
179+
expect(e).toBeInstanceOf(Error)
180+
expect(e).toBeInstanceOf(BaseError)
181+
expect(e).toBeInstanceOf(MyError)
182+
183+
expect(e.name).toBe('MyError')
184+
expect(e.message).toBe('my error message')
185+
expect(typeof e.stack).toBe('string')
186+
compareStacks(e.stack, stack)
187+
})
172188
})

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
"standard": "^10.0.3",
3333
"uglify-js": "^3.3.2"
3434
},
35+
"jest": {
36+
"testEnvironment": "node"
37+
},
3538
"scripts": {
3639
"commitmsg": "yarn test",
3740
"dev-test": "jest --watch",

0 commit comments

Comments
 (0)