gpt4 book ai didi

javascript类可访问性变量作用域问题

转载 作者:行者123 更新时间:2023-12-03 10:10:27 25 4
gpt4 key购买 nike

我正在编写一个简短的类(第一次在 Javascript 中使用类)来处理我的网站的菜单图标。该菜单图标需要能够在同一页面上多次实例化。

我在使用滚动事件触发函数时遇到问题,该函数似乎不会影响正确的类实例,这是我的伪代码:

var DynMenu = function(Name) {
this.Name = Name;

this.scrollHandler = function() {
alert("Scroll: "+this.Name);
};

DynMenu.prototype.Pause = function() {
alert("Pausing menu: "+this.Name);
$(window).off("scroll", this.scrollHandler);
};

DynMenu.prototype.Start = function() {
alert("Starting menu: "+this.Name);
$(window).scroll(this.scrollHandler);
};
}

此代码被调用并与以下内容一起使用:

var RevendMenu = new DynMenu("MenuIcon1");
RevendMenu.Start();
RevendMenu.Pause();

滚动页面时(在调用 RevendMenu.Start() 之后但在调用 RevendMenu.Pause() 之前),我收到消息“Scroll:未定义”

你能告诉我为什么我没有得到 this.Name 的值以及如何解决这个问题吗?

非常感谢问候弗洛伦特

最佳答案

浏览器中的事件处理程序可以将 this 设置为触发该事件的元素,或者在没有触发该事件的元素的情况下设置为全局对象。在浏览器中,全局对象是window

为了将其绑定(bind)到该方法所属的对象,您可以使用.bind():

$(window).off("scroll", this.scrollHandler.bind(this));

或者,在没有 .bind() 的旧版浏览器中,您可以在闭包中捕获 this:

var that = this;
$(window).off("scroll", function() {that.scrollHandler()});
<小时/>

有关工作原理的更详细说明,请参阅:How does the "this" keyword in Javascript act within an object literal?

关于javascript类可访问性变量作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30138336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com