首页 > 开发 > JS > 正文

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

2017-09-05 13:02:28  来源:网友分享

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

解决方案

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