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

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();
}

关于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


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();
	});

这篇文章可能有所帮助。http://www.ibm.com/developerworks/cn/...

【热门文章】
【热门文章】