javascript class 可访问性变量范围问题

javascript class accessibility variable scope issue

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

我在使用滚动事件触发函数时遇到一个问题,它似乎没有受到右侧 class 实例的影响,这是我的伪代码:

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: undefined"

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

非常感谢 问候 佛罗伦特

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

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

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

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

var that = this;
$(window).off("scroll", function() {that.scrollHandler()});

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