简体   繁体   English

无法访问函数javascript中的函数

[英]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() . 问题是当我尝试像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. 我试图将调用封装到$(document).ready() ,但没有帮助。

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. 在您的情况下,您正在创建一个构造函数, myLib是一个构造function ,而不仅仅是一个function ,并且您无法直接访问该函数的属性和方法,这就是您获得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). 因此,您需要获取myLib的实例才能调用get方法或访问其任何成员(方法)。

 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: MDN 函数参考中,您可以看到:

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. this关键字不引用当前正在执行的函数,因此即使在函数体内,您也必须按名称引用Function对象。

myLib is used for "libary", and you want to call this "get" method of libary. myLib用于“ libary”,您想调用此libary的“ get”方法。

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: 您应该使用myLib作为构造函数,即:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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