简体   繁体   中英

Cannot access function inside function javascript

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!

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 to Function objects by name, even within the function body.

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();

You should use myLib as a constructor ie:

var lib = new myLib();
lib.get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM