gpt4 book ai didi

javascript - 使用 require.js 加载原型(prototype)增强

转载 作者:行者123 更新时间:2023-12-03 08:24:21 25 4
gpt4 key购买 nike

我正在使用 require.js 加载我的模块,它通常工作正常。不过,我还有两个问题:

1) 如果您有一个类似辅助类的模块,并为现有原型(prototype)定义了额外的方法(例如 String.isNullOrEmpty),您将如何包含它们?您希望避免使用对模块的引用。

2) 也需要更改以使用 jQuery。我知道需要使用 jQuery,但我是否还需要传递 $

谢谢!

最佳答案

1) If you have a module that is like a helper class and defines additional methods for existing prototypes (such as String.isNullOrEmpty), how would you include them? You want to avoid using the reference to the module.

如果您需要扩展原型(prototype),那么不要返回值并将其用作require 的最后一个参数:

// helpers/string.js
define(function() {
String.prototype.isNullOrEmpty = function() {
//
}
});

// main.js
require(['moduleA', 'helpers/string'], function(moduleA) {

});

2) What needs to be changed to use jQuery, too. I understand that jQuery needs to be required but do I also need to pass on $?

jQuery 的唯一要求是你配置正确的路径

require.config({
paths: {
jquery: 'path/to/jquery'
}
});

require(['jquery', 'moduleB'], function($, moduleB) {
// Use $.whatever
});

在我看来没有必要使用 the version of RequireJS that has jQuery built into it因为这主要在 jQuery 不支持 AMD 时使用。

现在它确实如此,并且将它分开可以让您轻松地换出另一个库(想想 Zepto)。

关于javascript - 使用 require.js 加载原型(prototype)增强,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15267524/

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