Douglas Crockford的“Javascript:The Good Parts”第5.5章 [英] Douglas Crockford's “Javascript: The Good Parts” Chapter 5.5

查看:68
本文介绍了Douglas Crockford的“Javascript:The Good Parts”第5.5章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与问题非常相似

我的问题是关于示例代码的更多信息。

My question is more about the example code.

代码:

var eventuality = function (that) {
    var registry = {};
    that.fire = function (event) {
// Fire an event on an object. The event can be either
// a string containing the name of the event or an
// object containing a type property containing the
// name of the event. Handlers registered by the 'on'
// method that match the event name will be invoked.
        var array,
            func,
            handler,
            i,
            type = typeof event === 'string' ?
                    event : event.type;
// If an array of handlers exist for this event, then
// loop through it and execute the handlers in order.
        if (registry.hasOwnProperty(type)) {
            array = registry[type];
            for (i = 0; i < array.length; i += 1) {
                handler = array[i];
// A handler record contains a method and an optional
// array of parameters. If the method is a name, look
// up the function.
                func = handler.method;
                if (typeof func === 'string') {
                    func = this[func];
                }
// Invoke a handler. If the record contained
// parameters, then pass them. Otherwise, pass the
// event object.
                func.apply(this,
                    handler.parameters || [event]);
            }
        }
        return this;
    };
    that.on = function (type, method, parameters) {
// Register an event. Make a handler record. Put it
// in a handler array, making one if it doesn't yet
// exist for this type.
        var handler = {
            method: method,
            parameters: parameters
        };
        if (registry.hasOwnProperty(type)) {
            registry[type].push(handler);
        } else {
            registry[type] = [handler];
        }
        return this;
    };
    return that;
}

代码中,我不明白这一行, func = handler.method;

in the code , I don't understand this line, func = handler.method; .

这怎么办?我的意思是handler.method应该是未定义的,对吗?

How can this work ? I mean handler.method should be undefined, right ?

谢谢

推荐答案

handler 是存储在注册表中的对象

    array = registry[type];
    for (i = 0; i < array.length; i += 1) {
        handler = array[i];

它被添加到 that.on 方法:

    var handler = {
        method: method,
        parameters: parameters
    };
    if (registry.hasOwnProperty(type)) {
        registry[type].push(handler);
    } else {
        registry[type] = [handler];
    }

它显然有方法 property。

and it clearly has the method property.

这篇关于Douglas Crockford的“Javascript:The Good Parts”第5.5章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆