立即自执行函数和“this”
我想创建一个 javascript 库,所以我认为使其成为一个立即自动执行的函数将是一件很好的事情,可以确保范围安全和一切。
但现在我遇到了使用“this”关键字的问题,我不太明白。
我怎样才能使这样的代码正确工作?目前,它告诉我“图像”未定义。
(function() {
function lib() {
this.image = document.getElementById("image");
this.parts = [
{name: "part1", num: "1"}
];
this.init = function() {
$(parts).each(function() {
var partNum = this.num;
image.getElementById(partNum).addEventListener("click", function() {
toggleHighlight(partNum);
}, true);
});
};
}
window.lib = new lib();
})();
window.lib.init();
如何访问 image
属性?
I want to create a javascript library, so I thought making it an immediately self executing function would be a nice thing to do to ensure scope safety and everything.
But now I'm running into a problem with using the "this" keyword that I don't quite understand.
How can I make a code like this work correctly? Currently, it tells me that "image" is undefined.
(function() {
function lib() {
this.image = document.getElementById("image");
this.parts = [
{name: "part1", num: "1"}
];
this.init = function() {
$(parts).each(function() {
var partNum = this.num;
image.getElementById(partNum).addEventListener("click", function() {
toggleHighlight(partNum);
}, true);
});
};
}
window.lib = new lib();
})();
window.lib.init();
How can I access the image
property?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您在这里遇到了一些问题:
init
函数中引用parts
,而没有将其作为this
的属性进行访问。each
块中,您将image
作为全局变量进行访问,但它并未全局声明。您无法从该块中的this
访问image
,因为在该上下文中,this
实际上设置为您正在迭代的项目。 (这就是为什么您可以访问this.num
。)我建议您包含 var that = this;在你的 init 函数之前,并在访问诸如 that.image 之类的属性时使用它。
I think you have a few issues here:
parts
in yourinit
function without accessing it as a property ofthis
.each
block, you are accessingimage
as a global variable but it is not declared globally. You can't accessimage
fromthis
in that block because in that context,this
is actually set to the item you are iterating on. (That is why you can accessthis.num
.)I sugggest you include var that = this; before your init function and use it when accessing properties like that.image.
如果我理解正确,您希望从您提供给
each
的匿名函数访问在lib
函数内部定义的this.image
属性>。为此,您需要保留this
以使其在匿名函数中可用:If I understand you right you want to get access to
this.image
property defined inside oflib
function from the anonymous function which you provide to theeach
. To do this you need to preservethis
to make it available in the anonymous function:您还应该将函数名称
lib
的第一个字母大写,因为您希望将其用作具有new
关键字的构造函数。看看《Javascript The Good Parts》的作者对 JavaScript 中的构造函数命名约定。You should also capitalize the first letter of function name
lib
since you are expecting it to be used as a constructor with thenew
keyword. Take a look at what the author of Javascript The Good Parts has to say about constructor naming conventions in JavaScript.