簡體   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