鍍金池/ 問答/HTML/ self.dispatch.apply(self, args); 這個怎么理解?

self.dispatch.apply(self, args); 這個怎么理解?

/**
         * 添加一個組件實例到大屏中
         *
         * @param {Component} component 組件實例
         * @return {Screen}
         */
        addComponent: function (component) {
            var self = this;

            // 綁定組件的所有事件
            component.bind(function (event) {
                var args = Array.prototype.slice.call(arguments, 1);
                args.unshift(this);
                args.unshift('component.' + event);
                self.dispatch.apply(self, args);
            });

            // 添加到大屏中
            component.render(self.container);

            // 放入列表中
            self.componentsById[component.id] = component;

            return self;
        }
回答
編輯回答
司令

apply的用法

1.改變調(diào)用的函數(shù)作用域 this的值

function fn(){
    console.log(this.a);//我是obj
}
var obj = {a:"我是obj"}
fn.apply(obj);//將this指向obj

2.當不明確參數(shù)數(shù)量的時候可以吧數(shù)組轉(zhuǎn)換為參數(shù)

function fn(a, b, ...){
  console.log(a,b);// 1, 2
}
fn.apply(null,["1", "2"]);

這里改變后

var self = this;
component.bind(function (event, a, b, ...) {
    self.dispatch(this, 'component.' + event, a, b, ... );
});
2017年12月19日 00:08
編輯回答
青檸

遇到這種問題,你應(yīng)該先了解一下 apply 的意義。它表示執(zhí)行函數(shù),并且以第一個參數(shù)作為 context,第二個參數(shù)作為函數(shù)的參數(shù)依次傳入。

所以在這個地方,因為組件本身是通用的,有哪些事件,需要傳入哪些參數(shù)無法確定,所以只好使用 apply 的方式把所有事件全部傳到處理函數(shù)中。

2018年4月1日 15:53