如何解决使用原型在javascript中维护此指针
| 我在使用原型observe
函数和访问此指针时遇到问题。考虑以下:
var Demo = Class.create({
this.someValue = \"this is the value\",initialize: function() {
Event.observe(\"button1\",\"click\",function() {
alert(this.someValue);
});
Event.observe(\"button2\",this.testFunc());
},testFunc: function() {
alert(this.someValue);
}
});
同时单击“ 2”和“ 3”控件并不会执行我希望警报显示“这是值”的操作,而是显示事件的来源(即按钮)。所以我的问题是我如何才能实现自己的目标并使此指针等于Demo
类。
解决方法
从手册中:
原型的绑定功能可以进行救援。使用bind(),可以确保您的方法获得正确的
this
。
在您的示例中:
var Demo = Class.create({
initialize: function() {
this.someValue = \"this is the value\";
Event.observe(\"button1\",\"click\",(function() {
alert(this.someValue);
}).bind(this));
Event.observe(\"button2\",this.testFunc.bind(this));
},testFunc: function() {
alert(this.someValue);
}
});
, 在this
指向所需对象的范围内,将其分配给变量(例如self
),然后在this
不再指向所需对象的范围内引用变量。例:
/**
* @constructor
*/
var Demo = function(){};
/**
* Some value
* @type {string}
*/
Demo.prototype.someValue = \"this is the value\";
/**
* Initializes the demo.
*/
Demo.prototype.initialize = function() {
var self = this;
Event.observe(\"button1\",function() {
alert(self.someValue);
});
Event.observe(\"button2\",self.testFunc());
};
/**
* Prints the value
*/
Demo.prototype.testFunc = function() {
alert(this.someValue);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。