我正在尝试通过在脚本中使用命名空间并将函数设为私有(private)来定位 jquery 选择器
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Selectors</title>
</head>
<body>
<ul>
<li class="test">First</li>
<li>Second</li>
<li>Third</li>
</ul>
<!--<script>
$('document').ready(function(){
$('li.test').css('color','green')
})
</script>-->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var customModule = (function () {
var MyUtility = {
Selectors: {
ColorCss: function () {
var myBorder = function () {
$('li').css('color', 'red')
console.log('hello')
}
return{
myBorder: myBorder
}
}()
}
}
}())
</script>
</body>
</html>
最佳答案
正如你所说如果我尝试在最后一行添加断点并使用devtools访问MyUtility.Selectors.ColorCss.myBorder(),它就会起作用
这是您的代码:
var customModule = (function () {
var MyUtility = {
Selectors: {
ColorCss: function(){
var myBorder = function(){
$('li').css('color', 'red');
console.log('hello');
}
return{ myBorder: myBorder }
}()
} // Selectors
} // MyUtility
}())
上面的代码可以写成:
function myBorderFunc() { $('li').css('color', 'red'); console.log('hello');}
var selectorObj = { ColorCss : function(){ return{ myBorder: myBorderFunc } }()};
var MyUtility = { Selectors: selectorObj};
var customModule = ( function(){ MyUtility }() );
这说明了问题
var customModule
是一个不返回任何内容的函数表达式,因此它是undefined
- 由于
customModule
未定义,您无法使用customModule.MyUtility - 正如您所说,您可以调用
MyUtility.Selectors.ColorCss.myBorder()
因为MyUtility
是一个具有属性Selectors
的对象,并且等等
您可以通过以下示例进行测试:
// undefined since nothing is returned
var bar = (function(){ {Foo: "i am foo"} }());
// returns foo and can be used bar.Foo ---> "i am foo"
var bar = (function(){ return {Foo: "i am foo"} }());
要“修复您的代码”,请返回 MyUtility
var customModule = (function () {
var MyUtility = {
Selectors: {
ColorCss: function(){
var myBorder = function(){
$('li').css('color', 'red');
console.log('hello');
}
return{ myBorder: myBorder }
}()
} // Selectors
} // MyUtility
return MyUtility;
}())
这样您就可以像 customModule.Selectors.ColorCss.myBorder()
一样访问它。
关于javascript - 无法使用命名空间、模块化、私有(private)来定位选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824201/