[英]Namespace issue in javascript
即使使用名称空间,函数名称也会混合使用。 在下面的例子中,当我打电话nwFunc.callMe()
或$.Test1.callTest()
将执行_testFunction()
的doOneThing
。 我预期的$.Test1.callTest()
调用_testFunction()
在$.Test1
API,而不是一个在doOneThing
。 我需要做些什么来纠正它?
例:
var doOneThing = function() {
_testFunction= function() {
...
}
return {
// public
callMe: function(){
_testFunction();
}
}
}
var nwFunc = doOneThing();
nwFunc.callMe();
$.Test1.callTest();
jQuery.Test1 = (function(){
_testFunction= function() {
...// do differently
}
return {
// public
callTest: function(){
_testFunction()
}
}
}(jQuery))
您不在对象文字中,而是在函数体中。
_testFunction: function() { .... // do differently }
不是对象属性,而是带有标签的匿名函数表达式,由于未分配在任何地方,因此被立即遗忘。 改为使用简单的函数声明:
function _testFunction() {
.... // do differently
}
和
return { // public callMe() { _testFunction(); } }
只是语法错误,在这里您需要对象文字sytnax :
return {
// public
callTest: function() {
_testFunction()
}
};
要么
return {
// public
callTest: _testFunction // exporting the function directly
};
当我打电话
nwFunc.callMe()
或$.Test1.callTest()
将执行_testFunction()
的doOneThing
。 我需要做些什么来纠正它?
您必须使用var
声明将_testFunction
变量放在本地范围内。 目前,你写的全球范围内,只有一个_testFunction
存在(目前在doOneThing
你覆盖_testFunction
从jQuery.Test1
,都callTest
功能将调用新的一个)。 函数声明也可以使用本地范围来解决此问题,这类似于var语句+函数表达式 。
您正在稍微混淆语法。 最初声明函数时使用的是对象文字符号,而实际创建对象时使用的是函数声明符号,因此应将两者切换:
jQuery.Test1 = (function(){
function _testFunction() {
.... // do differently
}
return {
// public
callTest: _testFunction
}
}(jQuery))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.