想在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();
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
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/...
关于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-p").click(person.hello.bind(person));
// when the p is clicked, "Alex Russell says hello world" is printed