Home > OS >  How to make a function in a function
How to make a function in a function

Time:08-11

I am somewhat new to Javascript, and I am trying to make a library for myself, so I dont have to code it in later. I have this code (below).

function lib() {
  let _this = this;
  this.addstring= (n, d) => {
    return n   d
  }
}
console.log(lib.addstring("foo", "bar"))

When the code above is ran, it tells me that lib.addstring is not a function. How would I be able to write this as a function?

CodePudding user response:

You are using this incorrectly. You do not create lib instance, so you don't need this. If you wish to group everything on lib object, just wrap everything to the object:

const lib = {
  addstring(n, d) {
    return n   d
  }
}

console.log(lib.addstring("foo", "bar"))

CodePudding user response:

A nice way to do this would be ES6 modules. With ES6 modules, you would create a new file that uses the export keyword for every function you want to use externally. Here's an example:

library.mjs

export function addstring(n, d) {
  return n   d;
}

code.js

import {addstring} from './library.mjs';

console.log(addstring("foo", "bar"))
  • Related