我无法在 javascript 类/jQuery 插件的闭包范围内分配一些变量。
当我像在 Article 类的构造函数中那样进入 Article.initObj() 时,我在闭包范围内看不到domElement
or settings
,但我可以看到me
and testVar
。这让我很困惑。任何人都可以阐明这里可能发生的事情吗?
编辑:我在 Firefox 和 chrome 中都试过这个。
这是我的 HTML:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="ArticleNav.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Init our Viomedia article graph
var articleList = $("#entityList").children().ArticleNav();
});
</script>
</head>
<body>
<div id="leftPanel" class="vpanel">
<div id="#search">
<label for="searchField">Search </label>
<input style="float: right;" name="searchField" id="searchField"/>
</div>
<div id="tree">
</div>
</div>
<div id="rightPanel" class="vpanel">
<div id="entityList" >
<div class="article program" id="1">
<div class="title">The Simpsons</div>
<div class="article playlist" id="2">
<div class="title">Classic Episodes</div>
<div class="article episode" id="6">
<div class="title">Homer the Heretic</div>
</div>
</div>
<div class="article season" id="3">
<div class="title">Season 4</div>
<div class="article episode" id="4">
<div class="title">Kamp Krusty</div>
</div>
<div class="article episode" id="5">
<div class="title">A Streetcar Named Marge</div>
</div>
<div class="article episode" id="6">
<div class="title">Homer the Heretic</div>
</div>
<div class="article episode" id="7">
<div class="title">Lisa the Beauty Queen</div>
</div>
</div>
</div>
<div class="artist article" id="7">
<div class="title">Electric Light Orchestra</div>
<div class="article album" id="8">
<div class="title">The Essential Electric Light Orchestra</div>
<div class="article album" id="9">
<div class="title">Disc 1</div>
<div class="article track" id="10">
<div class="title">So Serious</div>
</div>
</div>
<div class="article album" id="11">
<div class="title">Disc 2</div>
<div class="article track" id="12">
<div class="title">Last Train to London</div>
</div>
</div>
</div>
</div>
<div class="program article" id="13">
<div class="title">Archer</div>
</div>
</div>
</div>
</body>
</html>
这是我的 jQuery 插件:
(function($){
var Article = function (element, options)
{
var me = this;
var testVar = "I can read this";
var domElement = $(element);
var settings = $.extend({}, options || {});
this.initObj = function()
{
me.test();
};
this.test = function()
{
console.log(testVar);
};
this.initObj();
};
var construct = function(element) {
var element = $(element);
// If this element already has this plugin attached to it.
if(element.data('Article')) {
return;
}
var ArticlePlugin = new Article(element);
element.data('Article', ArticlePlugin);
};
$.fn.ArticleNav = function(func) {
return this.each(function()
{
switch (func) {
default:
construct(this);
break;
}
});
};
}( jQuery ));