问题描述
|
我在使用原型
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);
};