├── index.d.ts ├── index.js ├── .gitignore ├── package.json ├── .github └── workflows │ └── node.js.yml ├── LICENSE ├── test ├── types.ts ├── esmodule.mjs └── require.js ├── README.md └── tsconfig.json /index.d.ts: -------------------------------------------------------------------------------- 1 | type Func = (...argv: Args) => Return; 2 | interface ICallableInstance { 3 | // prettier-ignore 4 | new (property: string | symbol): 5 | Func; 6 | } 7 | declare const CallableInstance: ICallableInstance; 8 | export = CallableInstance; 9 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | function CallableInstance(property) { 2 | var func = this.constructor.prototype[property]; 3 | var apply = function () { 4 | return func.apply(apply, arguments); 5 | }; 6 | Object.setPrototypeOf(apply, this.constructor.prototype); 7 | Object.getOwnPropertyNames(func).forEach(function (p) { 8 | Object.defineProperty(apply, p, Object.getOwnPropertyDescriptor(func, p)); 9 | }); 10 | return apply; 11 | } 12 | CallableInstance.prototype = Object.create(Function.prototype); 13 | 14 | module.exports = CallableInstance; 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | /dist 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "callable-instance", 3 | "version": "2.0.0", 4 | "description": "Instances of classes which are directly callable as functions.", 5 | "repository": "CGamesPlay/node-callable-instance", 6 | "main": "index.js", 7 | "types": "index.d.ts", 8 | "scripts": { 9 | "test": "mocha && tsc" 10 | }, 11 | "keywords": [ 12 | "instance", 13 | "function", 14 | "object", 15 | "class", 16 | "callable" 17 | ], 18 | "bugs": { 19 | "url": "https://github.com/CGamesPlay/node-callable-instance/issues" 20 | }, 21 | "author": "Ryan Patterson", 22 | "license": "MIT", 23 | "devDependencies": { 24 | "@types/mocha": "^10.0.1", 25 | "mocha": "^10.2.0", 26 | "prettier": "^2.8.1", 27 | "ts-expect": "^1.3.0", 28 | "typescript": "^4.9.4" 29 | }, 30 | "files": [ 31 | "index.js", 32 | "index.d.ts", 33 | "LICENSE", 34 | "README.md" 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [14.x, 16.x, 18.x, 19.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v3 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | cache: 'npm' 29 | - run: npm ci 30 | - run: npm run build --if-present 31 | - run: npm test 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Ryan Patterson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/types.ts: -------------------------------------------------------------------------------- 1 | import { expectType } from "ts-expect"; 2 | 3 | import CallableInstance from "../index.js"; 4 | 5 | class Repeater extends CallableInstance<[string], string> { 6 | constructor(public count: number) { 7 | super("go"); 8 | } 9 | 10 | go(arg: string): string { 11 | return arg.repeat(this.count); 12 | } 13 | } 14 | 15 | describe("CallableInstance (TypeScript)", function () { 16 | it("is callable", function () { 17 | expectType<(x: string) => string>(new Repeater(1)); 18 | // @ts-expect-error wrong type for constructor 19 | new Repeater("testing"); 20 | // @ts-expect-error wrong type for method 21 | new Repeater(5).go(5); 22 | // Valid propert access. 23 | new Repeater(5).count = 4; 24 | }); 25 | 26 | it("is an object", function () { 27 | expectType(new Repeater(5)); 28 | expectType<(x: string) => string>(new Repeater(5).go); 29 | }); 30 | 31 | it("is an instance of Repeater", function () { 32 | expectType(new Repeater(5)); 33 | //expectType(new Repeater(5)); 34 | expectType(new Repeater(5)); 35 | expectType(new Repeater(5)); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /test/esmodule.mjs: -------------------------------------------------------------------------------- 1 | import assert from "assert"; 2 | import CallableInstance from "../index.js"; 3 | 4 | class MyTest extends CallableInstance { 5 | constructor(message) { 6 | super("go"); 7 | this.message = message; 8 | } 9 | 10 | go(arg) { 11 | return arg || this.message; 12 | } 13 | } 14 | 15 | describe("CallableInstance (mjs)", function () { 16 | it("is callable", function () { 17 | assert(new MyTest("testing")() === "testing"); 18 | assert(new MyTest()("arg") === "arg"); 19 | }); 20 | 21 | it("is an object", function () { 22 | assert(new MyTest("testing").go() === "testing"); 23 | }); 24 | 25 | it("is an instance of MyTest", function () { 26 | assert(new MyTest("testing") instanceof MyTest); 27 | assert(new MyTest("testing") instanceof CallableInstance); 28 | assert(new MyTest("testing") instanceof Function); 29 | assert(new MyTest("testing") instanceof Object); 30 | }); 31 | 32 | it("is a function", function () { 33 | assert(typeof new MyTest("testing") === "function"); 34 | }); 35 | 36 | it("copies the name property", function () { 37 | assert(new MyTest("testing").name === "go"); 38 | }); 39 | 40 | it("copies the length property", function () { 41 | assert(new MyTest("testing").length === 1); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /test/require.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var assert = require("assert"); 4 | var CallableInstance = require("../index"); 5 | 6 | class MyTest extends CallableInstance { 7 | constructor(message) { 8 | super("go"); 9 | this.message = message; 10 | } 11 | 12 | go(arg) { 13 | return arg || this.message; 14 | } 15 | } 16 | 17 | describe("CallableInstance (require)", function () { 18 | it("is callable", function () { 19 | assert(new MyTest("testing")() === "testing"); 20 | assert(new MyTest()("arg") === "arg"); 21 | }); 22 | 23 | it("is an object", function () { 24 | assert(new MyTest("testing").go() === "testing"); 25 | }); 26 | 27 | it("is an instance of MyTest", function () { 28 | assert(new MyTest("testing") instanceof MyTest); 29 | assert(new MyTest("testing") instanceof CallableInstance); 30 | assert(new MyTest("testing") instanceof Function); 31 | assert(new MyTest("testing") instanceof Object); 32 | }); 33 | 34 | it("is a function", function () { 35 | assert(typeof new MyTest("testing") === "function"); 36 | }); 37 | 38 | it("copies the name property", function () { 39 | assert(new MyTest("testing").name === "go"); 40 | }); 41 | 42 | it("copies the length property", function () { 43 | assert(new MyTest("testing").length === 1); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-callable-instance 2 | 3 | [![Build Status](https://img.shields.io/github/actions/workflow/status/CGamesPlay/node-callable-instance/node.js.yml?branch=master)](https://github.com/CGamesPlay/node-callable-instance/actions/workflows/node.js.yml) [![Download Size](https://img.shields.io/bundlephobia/min/callable-instance.svg?style=flat)](https://bundlephobia.com/package/callable-instance@latest) [![dependencies](https://img.shields.io/badge/dependencies-none-brightgreen)](https://www.npmjs.com/package/callable-instance?activeTab=dependencies) [![npm](https://img.shields.io/npm/v/callable-instance)](https://www.npmjs.com/package/callable-instance) [![npm](https://img.shields.io/npm/dw/callable-instance)](https://www.npmjs.com/package/callable-instance) 4 | 5 | This module allows you to create an ES6 class that is callable as a function. The invocation is sent to one of the object's normal prototype methods. 6 | 7 | ## Installation 8 | 9 | ``` 10 | npm install callable-instance 11 | ``` 12 | 13 | ## Usage 14 | 15 | In the following example, we will create an `ExampleClass` class. The instances have all of the normal properties and methods, but are actually functions as well. 16 | 17 | ```javascript 18 | import CallableInstance from "callable-instance"; 19 | // If you aren't using ES modules, you can use require: 20 | // var CallableInstance = require("callable-instance"); 21 | 22 | class ExampleClass extends CallableInstance { 23 | constructor() { 24 | // CallableInstance accepts the name of the property to use as the callable 25 | // method. 26 | super("instanceMethod"); 27 | } 28 | 29 | instanceMethod() { 30 | console.log("instanceMethod called!"); 31 | } 32 | } 33 | 34 | var test = new ExampleClass(); 35 | // Invoke the method normally 36 | test.instanceMethod(); 37 | // Call the instance itself, redirects to instanceMethod 38 | test(); 39 | // The instance is actually a closure bound to itself and can be used like a 40 | // normal function. 41 | test.apply(null, [1, 2, 3]); 42 | ``` 43 | 44 | TypeScript is also supported. `CallableInstance` is generic, accepting a tuple of arguments and a return type. 45 | 46 | ```typescript 47 | import CallableInstance from "callable-instance"; 48 | 49 | class ExampleClass extends CallableInstance<[number], string> { 50 | constructor() { 51 | super("instanceMethod"); 52 | } 53 | 54 | instanceMethod(input: number): string { 55 | return `${input}`; 56 | } 57 | } 58 | ``` 59 | 60 | Note that the types specified may differ from the argument and return value types of the target method; this is an error due to a limitation of TypeScript. 61 | 62 | 63 | ### Inherited Properties 64 | 65 | All instances of CallableMethod are also an instances of [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), and have all of Function's properties. 66 | 67 | Libraries that accept functions will expect that they behave as Function objects do. For example, if you alter the semantics of the `call` or `apply` methods, library code may fail to work with your callable instance. In these cases, you can simply bind the instance method to the callable instance and pass that instead (e.g. `test.instanceMethod.bind(test)`). 68 | 69 | This can also cause problems if your derived class wants to have a `name` or `length` property, which are built-in properties and not configurable by default. You can have your class disable the built-in descriptors of these properties to make them available for your use. 70 | 71 | ```javascript 72 | var test = new ExampleClass(); 73 | test.name = "hello!"; 74 | console.log(test.name); // Will print 'instanceMethod' 75 | 76 | class NameableClass extends CallableInstance { 77 | constructor() { 78 | super("instanceMethod"); 79 | Object.defineProperty(this, "name", { 80 | value: void 0, 81 | enumerable: true, 82 | writeable: true, 83 | configurable: true, 84 | }); 85 | } 86 | 87 | instanceMethod() { 88 | console.log(this.name); 89 | } 90 | } 91 | 92 | test = new NameableClass(); 93 | test.name = "hello!"; 94 | console.log(test.name); // Will print 'hello!' 95 | ``` 96 | 97 | ## Contributing 98 | 99 | 1. Fork it! 100 | 2. Create your feature branch: `git checkout -b my-new-feature` 101 | 3. Commit your changes: `git commit -am 'Add some feature'` 102 | 4. Push to the branch: `git push origin my-new-feature` 103 | 5. Submit a pull request :D 104 | 105 | ## Credits 106 | 107 | Information for the implementation came from [this StackOverflow answer](http://stackoverflow.com/a/36871498/123899). 108 | 109 | ## License 110 | 111 | Distributed under the MIT license. 112 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs" /* Specify what module code is generated. */, 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "resolveJsonModule": true, /* Enable importing .json files. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 45 | 46 | /* Emit */ 47 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 48 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 52 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 53 | // "removeComments": true, /* Disable emitting comments. */ 54 | "noEmit": true /* Disable emitting files from a compilation. */, 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 74 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 77 | 78 | /* Type Checking */ 79 | "strict": true /* Enable all strict type-checking options. */, 80 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 81 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | } 103 | } 104 | --------------------------------------------------------------------------------