这个是微博页面写的:
<script src="js/lib/r.js" data-main="js/page/weibo"></script>
这是weibo.js
里写的
require(["../modules/move","../modules/weiboFunc"],function(move,weiboFunc){
var weibo = {
init:function(){
this.picResize();
this.weiboFunc();
// this.getRepost();
},
//微博图片的缩略功能
picResize:function(){}
weibo.init();
});
然后页面初始化的时候就出现了这个错误,
ReferenceError: getNodeByClassName is not defined
getNodeByClassName ()是第一个模块,move模块中的方法
move.js里是这样写的:
define(function(){
function getNodeByClassName (){
//code
};
});
求问大家,为什么会出现getNodeByClassName is not defined
?
我们编写一个模块(A),然后让另外一个模块(B)可以调用它,其道理是要返回一个可以访问的对象(函数也是对象)。像这样定义模块:
javascript
/* move.js */ define(function(){ function getNodeByClassName (){ //code } });
你没有返回任何东西,那么你让 B 引用这个模块的时候到底要去调用什么呢?仔细想想这个问题!
所以,我们最起码应该这样写:
javascript
/* Don't name it as `move.js`, because it doesn't reflect what exactly it is! * Instead, you should name it like `domUtilities.js` or something like that. */ define(function() { function getNodeByClassName() { // code... } return getNodeByClassName; // IMPORTANT!!! });
于是这个模块的确返回了些什么,然后引用它的其他模块才能真正的访问到什么:
javascript
require(["../modules/domUtilities"], function(getNodeByClassName) { console.log(getNodeByClassName); // Thus you can use it. });
通常一个模块不止要返回一个函数而是一组函数,所以我们需要用某种模式封装一下,最常用也最简单就是字面量对象:
javascript
/* domUtilities.js */ define(function() { function getNodeByClassName() { // code... } function getNodeByTagName() { // code... } ... return { getNodeByClassName: getNodeByClassName, getNodeByTagName: getNodeByTagName, ... }; // AGAIN, IMPORTANT!!! });
于是,我们可以:
javascript
require(["../modules/domUtilities"], function(domUtilities) { console.log( domUtilities.getNodeByClassName, domUtilities.getNodeByTagName, ... ); // Thus you can use it. });
这就是为什么浏览器说你调用的函数未定义的原因,你的模块没有返回它,调用的时候当然找不到。