Reputation: 662
I'm trying to clean my code a bit, so I create some small objects or libraries (call it how you want) like:
function myLib() {
this.get = function() { ... };
...
};
Problem is when I try to call it like myLib.get()
. It throws the following error:
Uncaught TypeError: myLib.get is not a function
I've tried to encapsulate the call into $(document).ready()
, but it did not help.
Can you help me, please?
Thanks!
Upvotes: 1
Views: 1164
Reputation: 703
myLib is used for "libary", and you want to call this "get" method of libary.
Static instance is better in your case.
const myLib = {
get:function(){},
get2:function(){}
...
};
myLib.get();
myLib.get2();
Upvotes: 2
Reputation: 32175
so I create some small objects or libraries (call it how you want)
In your case you are creating a constructor, myLib
is a constructor and not just a function
, and you can't access a function's properties and methods directly that's why you got the Exception.
So you need to get an instance of myLib
in order to call the get
method or to access any of its members(methods).
function myLib() {
this.get = function() { console.log("get called!!"); };
};
let lib = new myLib();
lib.get();
Note:
And from the MDN Reference for Functions you can see that:
The
this
keyword does not refer to the currently executing function, so you must refer toFunction
objects by name, even within the function body.
Upvotes: 2
Reputation: 911
You should use myLib as a constructor ie:
var lib = new myLib();
lib.get();
Upvotes: 1