繁体   English   中英

javascript对象 - 如何在类函数内调用类变量

[英]javascript object - how to call class variable inside class function

我想在用户点击div时调用变量“info”

应该打印“成功”的代码

但它的印刷品“未定义”

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



}

的jsfiddle

我的目标

  • 我需要在Controller监听器中调用变量“info”
  • 我需要在Controller set中单击动作

我的问题是在函数“listener”中,

关键字“this”是指div元素,而不是类Controller

如何在函数“ listener ”中调用变量信息?

尝试

var Controller = function(){
  var self = this; // Add this
  this.info = '  success  ';
  this.listener = function(){
    alert( self.info ); // Modify here
  }
....

您可以使用bind的功能结合到右侧this

ele.onclick = this.listener.bind(this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM