Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix exception on older browsers #246

Merged
merged 9 commits into from
Jun 19, 2024
4 changes: 3 additions & 1 deletion lib/callable-instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ export const CallableInstance =

for (const p of names) {
const descriptor = Object.getOwnPropertyDescriptor(value, p)
if (descriptor) Object.defineProperty(apply, p, descriptor)
if (descriptor && descriptor.configurable) {
Object.defineProperty(apply, p, descriptor)
}
}

return apply
Expand Down
70 changes: 70 additions & 0 deletions test/callable-instance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {CallableInstance} from '../lib/callable-instance.js'

test('callable-instance', async function (t) {
await t.test('can invoke ES6 class', async function () {
class Es6Class extends CallableInstance {
constructor() {
super('copy')

/** @type {number} */
this.foo = 42
/** @type {number} */
this.bar = 0
}

/** @returns {Es6Class} */
copy() {
const destination = new Es6Class()
destination.foo = this.foo
destination.bar = this.bar
return destination
}
}

const instance = new Es6Class()
assert.strictEqual(instance.foo, 42)

instance.bar = 100

// Instance is callable
/** @type {Es6Class} */
const copied = instance()
assert.strictEqual(copied.foo, 42)
assert.strictEqual(copied.bar, 100)
})

await t.test('can invoke new (ES5 class)', async function () {
function Es5Class() {
/** @type {Function} */
const callableInstance = CallableInstance
return callableInstance.call(this, ['copy'])
}

Es5Class.prototype.foo = 42 // type-coverage:ignore-line
Es5Class.prototype.bar = 0 // type-coverage:ignore-line

// type-coverage:ignore-next-line
Es5Class.prototype.copy = function () {
const destination = new Es5Class()
destination.foo = this.foo
destination.bar = this.bar
return destination
}

// Es5Class is newable
const instance = new Es5Class()
assert.strictEqual(instance.foo, 42)

/** @type {number} */
instance.bar = 100

// Instance is callable
/** @type {Es5Class} */
// @ts-expect-error Es5Class is also callable
const copied = instance()
assert.strictEqual(copied.foo, 42)
assert.strictEqual(copied.bar, 100)
})
})
1 change: 1 addition & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable import/no-unassigned-import */
import './callable-instance.js'
import './core.js'
import './data.js'
import './freeze.js'
Expand Down