gpt4 book ai didi

javascript - 对 require JS 感到困惑

转载 作者:行者123 更新时间:2023-11-28 18:37:19 26 4
gpt4 key购买 nike

考虑以下示例:

var ExampleFunction = function(param1, param2) {
this.helloWorld = function() {
console.log('hello world' + param1 + param2);
}
}

当我做类似的事情时:

require(['https://path/to/example_function.js'], function(exampleFunction){
console.log(exampleFunction);
});

我明白了:

define( function() { return function(param1, param2) {
this.helloWorld = function() {
console.log('hello world' + param1 + param2);
}
} } );

如何注入(inject)该函数的依赖项?我似乎无法实例化我自己通过调用注入(inject)它们的函数。

此外,当本地加载时,我可以这样做:

var exampleFunction = new ExampleFunction(someParam, someOtherParam);

但是当从服务器加载时我不能。

想法?

最佳答案

如果您使用的脚本不是 RequireJS 格式(包装在 Define() 中),则必须将它们填充到您的 require 配置中,以便可以正确加载它们:

require.config({
paths: {
"exampleFunction": "https://path/to/example_function.js"
},

shim: {
"exampleFunction": {
exports: "exampleFunction"
}
}
});

然后像这样使用它们

require(["exampleFunction"], function(exampleFunction){
new exampleFunction(param1, param2);
});

有关该主题的更多信息 http://requirejs.org/docs/api.html#config-shim

关于javascript - 对 require JS 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com