Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中创建事件_Javascript_Javascript Objects - Fatal编程技术网

在Javascript中创建事件

在Javascript中创建事件,javascript,javascript-objects,Javascript,Javascript Objects,如果我有一个用作事件订阅的函数列表,那么运行它们并使用.call()(下面的B)或更直接地(a)调用它们是否有好处?代码如下。我能看到的唯一区别是,使用.call可以控制此设置为什么。除此之外还有什么区别吗 $(function() { eventRaiser.subscribe(function() { alert("Hello"); }); eventRaiser.subscribe(function(dt) { alert(dt.toString()

如果我有一个用作事件订阅的函数列表,那么运行它们并使用
.call()
(下面的B)或更直接地(a)调用它们是否有好处?代码如下。我能看到的唯一区别是,使用
.call
可以控制此
设置为什么。除此之外还有什么区别吗

    $(function() {
        eventRaiser.subscribe(function() { alert("Hello"); });
        eventRaiser.subscribe(function(dt) { alert(dt.toString()); });

        eventRaiser.DoIt();
    });

    var eventRaiser = new (function() {
        var events = [];
        this.subscribe = function(func) {
            events.push(func);
        };

        this.DoIt = function() {
            var now = new Date();
            alert("Doing Something Useful");
            for (var i = 0; i < events.length; i++) {
                events[i](now);  //A
                events[i].call(this, now);  //B
            }
        };
    })();
$(函数(){
订阅(函数(){alert(“Hello”);});
subscribe(函数(dt){alert(dt.toString());});
eventRaiser.DoIt();
});
var eventRaiser=new(函数(){
var事件=[];
this.subscribe=函数(func){
事件推送(func);
};
this.DoIt=函数(){
var now=新日期();
警惕(“做有用的事”);
对于(var i=0;i
不,没有其他区别。但是,如果您遵循第二种方法,则可以扩展
subscribe
,以便“客户机”可以指定要使用的上下文:

this.subscribe = function(func, context) {
     events.push({func: func, context: context || this});
};

this.DoIt = function() {
    var now = new Date();
    alert("Doing Something Useful");
    for (var i = 0; i < events.length; i++) {
        events[i].func.call(events[i].context, now);
    }
 };
this.subscribe=函数(func,context){
push({func:func,context:context | | this});
};
this.DoIt=函数(){
var now=新日期();
警惕(“做有用的事”);
对于(var i=0;i
如果您决定使用方法B,您可以允许订阅事件的函数执行特定于事件的函数


例如,可以在函数中使用
this.getDate()
(必须创建方法),而不是将日期作为参数传递。事件类中另一个有用的方法是
this.getTarget()

,这是一个很好的答案……谢谢!