简体   繁体   English

在JavaScript中的对象内部调用对象函数

[英]Call object function inside object in javascript

I'm trying to create a javascript class and instantiate some objects of it from HTML on load. 我正在尝试创建一个javascript类,并在加载时实例化它的某些对象。 The class contains some functions and some event listeners. 该类包含一些函数和一些事件侦听器。

function Rating (id) 
{
    this.id = id;

    $(id).click(function() 
    {
        alert('click '+ this.id);
        this.debug();
    });

    this.debug = function() 
    {
        alert(' debug');
    }
  }

My goal is to call a class function from an event listener (in this case debug inside click listener). 我的目标是从事件监听器调用类函数(在这种情况下,是在点击监听器中debug )。 Unfortunately, when I click on the object I only see the event-listener alert and not debug alert ( fiddle ). 不幸的是,当我单击对象时,我只会看到事件监听器警报,而看不到调试警报( 小提琴 )。

I know it's a basic question. 我知道这是一个基本问题。 But all answers I've found explain to create classes as variables, not as functions. 但是我找到的所有答案都说明了将类创建为变量而不是函数。 I've adopted this way because my goal is to create multiple instances of the class into the same page. 我之所以采用这种方式,是因为我的目标是在同一页面中创建该类的多个实例。 Is there a way to instantiate multiple objects using "variable classes" and call internal functions from objects? 有没有一种方法可以使用“变量类”实例化多个对象并从对象中调用内部函数? Thanks in advance. 提前致谢。

Classical one, the context in the event handler is window . 经典的事件处理程序中的上下文是window

The simplest solution is to declare a variable in the enclosing scope to store the value you need : 最简单的解决方案是在封闭范围内声明一个变量,以存储所需的值:

function Rating (id) 
{
    var r = this;
    this.id = id;

    $(id).click(function() {
        alert('click '+ r.id);
        r.debug();
    });

    this.debug = function() 
    {
        alert(' debug');
    }
  }

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

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