我想在用户点击 div 时调用变量“info”
应该打印“成功”的代码
但是它的打印是“undefined”
html
<div id="container" style="width: 100px; height: 100px; border: solid black 1px">
javascript
window.onload = function(){
var Controller = function(){
this.info = ' success ';
this.listener = function(){
alert( this.info );
}
this.set = function( ele ){
ele.onclick = this.listener;
}
}
var target = document.getElementById('container');
var controller = new Controller();
controller.set( target );
}
我的目标
- 我需要在 Controller listener 中调用变量“info”
- 我需要在 Controller set 中点击操作
我的问题是 内部函数“监听器”,
关键字“this”指的是 div 元素,而不是类 Controller
如何在函数“listener”中调用变量信息?
最佳答案
尝试
var Controller = function(){
var self = this; // Add this
this.info = ' success ';
this.listener = function(){
alert( self.info ); // Modify here
}
....
关于javascript对象 - 如何在类函数中调用类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440287/