简体   繁体   English

在我自己的类中使用JavaScript库(underscore.js)

[英]Using a javascript library (underscore.js) within a class of my own

I'm trying to call a method from the underscore.js library within a class of my own. 我正在尝试从我自己的类中的underscore.js库中调用方法。 Something like this: 像这样:

document.write('<scr'+'ipt type="text/javascript" src="Helpers/underscore-min.js" ></scr'+'ipt>');
function MyObject(object){
    this.object = object;

    this.RandomMethod = function(object)
    {
        var result = _.isEqual(object, this);
    }
}

I am able to use it if I do it outside of the object declaration, but if it try to access it like this, the object does not exist. 如果我在对象声明之外进行操作,则可以使用它,但是如果它尝试像这样访问它,则该对象不存在。

Can somebody help? 有人可以帮忙吗?

The script you are adding has not had time to load yet since scripts are loaded asynchronously. 由于脚本是异步加载的,因此您添加的脚本还没有时间加载。 To test this, try adding a timeout to delay the script execution: 要对此进行测试,请尝试添加超时以延迟脚本执行:

document.write('<scr'+'ipt type="text/javascript" src="Helpers/underscore-min.js" ></scr'+'ipt>');
setTimeout(function() {
    //your code here
}, 2000); //delay for 2 seconds to give script time to laod

This isn't a solution, just a way to verify the problem. 这不是解决方案,只是一种验证问题的方法。 If this is what's going on check out this article: 如果这是怎么回事,请查看本文:

4 ways to dynamically load external JavaScript(with source) 动态加载外部JavaScript的4种方法

You may want to employ the fourth option. 您可能需要采用第四个选项。 It allows you to determine when the script has finished loading. 它使您可以确定脚本何时完成加载。

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

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