1

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?

question answered by @traynor in comments
bmp
  • 31
  • 1
  • 7
  • 1
    Replace this.add... with lib.add... However, this would only make sense if the function was called first. You could create an IIFE from the function. – Wiktor Zychla Aug 10 '22 at 20:21
  • 1
    [Create method inside function](https://stackoverflow.com/questions/22541712/create-method-inside-function), [How do you create a method for a custom object in JavaScript?](https://stackoverflow.com/questions/504803/how-do-you-create-a-method-for-a-custom-object-in-javascript) – traynor Aug 10 '22 at 20:31
  • @traynor oh... I did not realize that this had already been answered. It was hard for me to search for a post because I did not really know what this would be called. Thanks. – bmp Aug 12 '22 at 20:24

2 Answers2

2

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"))
KiraLT
  • 2,385
  • 1
  • 24
  • 36
  • This is already what I have, I dont want it to be a variable object. Thanks, though. – bmp Aug 12 '22 at 20:27
1

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"))
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Thanks! This is helpful, but I accidentally forgot to mention I was using Node and not ES6. – bmp Aug 12 '22 at 20:20
  • Node.js supports ES6. ES6 is just a newer version of the javascript specification. All recent versions of major browsers and node.js support it. – Michael M. Aug 13 '22 at 21:20
  • The problem is, I'm not using Node in a browser environment... if i go into the package.json and change it, none of my other functions will work. It's just my terrible code setup – bmp Aug 15 '22 at 11:47
  • If you're not using not in a browser environment, it will still support ES6 modules, you just need to add `"type": "module"` in your package.json. Sorry if I didn't have that clear in my answer. – Michael M. Aug 15 '22 at 19:46