【问题标题】:Event manager - this undefined in callback function事件管理器 - 在回调函数中未定义
【发布时间】:2013-09-18 06:19:28
【问题描述】:

我正在尝试创建一个自定义 javascript EventManager 类并添加一些回调函数。但是当回调函数被调用时,函数中的'this'对象是未定义的。我查看了Custom Javascript EventManager - please help me complete,但这并不能完全回答我的问题。

为什么 this 和 this.name 在 this.onEvent 中没有定义?请帮忙,谢谢。

这是我的 jsfiddle:http://jsfiddle.net/Charissima/fswfv/3/

function arEventManager()   {

    this.callbacks = {};            

    this.addCallback = function(eventCategory, fn) {
        if (!this.callbacks[eventCategory]) {
            this.callbacks[eventCategory] = [];
        }
        if (fn instanceof Function) {
            this.callbacks[eventCategory].push(fn);
        }
        return this;
    }, // addCallback

    this.dispatchEvent = function(eventCategory, params) {
        // Callback-Funktion(en) ausloesen
        for (var iC = 0, lC = this.callbacks[eventCategory].length; iC < lC; iC++) {
            console.log( this.callbacks[eventCategory][iC] );
            this.callbacks[eventCategory][iC](params);
        }
    } // dispatchEvent              
};

function arPerson() {
    this.name;
    this.setName = function(name) {
        this.name = name;
    },
    this.getName = function() {
        return (this.name);
    },
    this.onEvent = function(p2) {
        alert('this.name = ' + this.name + ' / ' + 'p2.name = ' + p2.name);

    }
};


var eventManager = new arEventManager;

var Thomas = new arPerson();    
Thomas.setName('Thomas');

var Mike = new arPerson();  
Mike.setName('Mike');   

eventManager.addCallback("myEvent", Mike.onEvent);

function test() {
    eventManager.dispatchEvent('myEvent', Thomas);
}

【问题讨论】:

  • 一个新函数创建一个新作用域,具有不同的this

标签: javascript jquery oop


【解决方案1】:

这是因为你在调用函数时没有使用callapply,而是在没有上下文的情况下调用它。例如:

  • x.func() 调用 x.func 使得函数内的 this 引用 x

  • var func = x.func; func(); 调用 x.func,但没有为 this 指定值。

  • x.func.call(y); 调用 x.func 使得函数内的 this 引用 y

您可以使用bind 将上下文绑定到函数,您需要将其绑定到 SHIM 以实现浏览器兼容性:

eventManager.addCallback("myEvent", Mike.onEvent.bind(Mike));

Updated JSFiddle

【讨论】:

    【解决方案2】:

    将名称变量设为私有?

    Javascript (arPerson)

    function arPerson() {
        var name;
        this.setName = function(nm) {
            name = nm;
        },
        this.getName = function() {
        return (name);
        },
        this.onEvent = function(p2) {
            alert('this.name = ' + name + ' / ' + 'p2.name = ' + p2.getName());
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多