gpt4 book ai didi

javascript - 为什么使用 requirejs 定义模块时需要返回?

转载 作者:行者123 更新时间:2023-12-03 11:15:17 24 4
gpt4 key购买 nike

以下是我的代码:

HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Using Require js for modular loading of scripts.</title>
<!--Requirejs first loads the module that is specified in data-main .. So it will load the module init,init has two dependencies first is knockout so it loads the knockout first, then myAppViewModel next -->
<script type="text/javascript" data-main="scripts/init.js" src="scripts/require.js"></script>
</head>
<body>
Name : <span data-bind="text: myName"></span>
</body>
</html>

init.js

require(['knockout-3.2.0', 'myAppViewModel'], function(ko, myAppViewModel) {
ko.applyBindings(myAppViewModel());
});

myAppViewModel.js

define(function () {
return function myAppViewModel() {
this.myName = 'Sudheer';
};
});

如果我删除上面函数中的 return 。它说 myAppViewModel() 不是构造函数。为什么在这种情况下需要返回?

最佳答案

Require js 调用您传递给 define() 的函数以获得模块的实例。因此,无论您从外部函数返回什么,它都会作为您的模块获得。

如果您从代码中删除 return ,则外部函数不会返回任何内容,因此 Require js 为您的模块获取的值是 undefined

这就是为什么您需要 return 语句。

http://requirejs.org/docs/api.html#funcmodule

关于javascript - 为什么使用 requirejs 定义模块时需要返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372814/

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