JS里在闭包中对this引用的困惑

想在js里实现类的封装,遇到一个问题。具体的请看代码。问题见注释

var TestClass;

if (TestClass == undefined) {
  TestClass = function(){
  }
}
TestClass.prototype.init = function (options) {
	$(".alert_click").click(function(){
		this.popup("test");
                //这样的代码会提示popup未定义。如果想在此处调用popup应该怎么做?
	});
};
TestClass.prototype.popup = function (value) {
	alert(value);
}

			
$(function(){
	var testClass = new TestClass();
	testClass.init();
}
阅读 9.7k
4 个回答
var TestClass;

if (TestClass == undefined) {
  TestClass = function(){
  }
}
	TestClass.prototype.init = function (options) {
		var self = this;
        $(".alert_click").click(function(){
                self.popup("test");//访问闭包里的this
                //这样的代码会提示popup未定义。如果想在此处调用popup应该怎么做?
        });
	};
	TestClass.prototype.popup = function (value) {
		    alert(value);
	}

                        
	$(function(){
        var testClass = new TestClass();
        testClass.init();
	});
新手上路,请多包涵

关于js中的this,你记住谁调用,this就指向谁

你的那个this指向的是$(".alert_click")

要访问闭包的this,只要定义个变量缓存下来就好了。我一般喜欢var _this = this;

var person = {
name: "Alex Russell",
hello: function() { console.log(this.name + " says hello world"); }
}

$("#some-div").click(person.hello.bind(person));

// when the div is clicked, "Alex Russell says hello world" is printed

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题