js:實現自訂事件對象介面

來源:互聯網
上載者:User

標籤:

網易2017內推筆試題

要求:

  請實現下面的自訂事件Event對象的介面,功能見注釋(測試1)

  該Event對象的介面需要能被其他對象拓展複用(測試2)

 1     //測試1 2     Event.on(‘test‘,function(result){ 3         console.log(result); 4     }); 5     Event.on(‘test‘,function(){ 6         console.log(‘test‘); 7     }); 8     Event.emit(‘test‘,‘hello world‘);   //輸出‘hello world‘ 和 ‘test‘ 9     //測試210     var person1 = {};11     var person2 = {};12     Object.assign(person1, Event);13     Object.assign(person2, Event);14     person1.on(‘call1‘,function(){15         console.log(‘person1‘);16     });17     person2.on(‘call2‘,function(){18         console.log(‘person2‘);19     });20     person1.emit(‘call1‘);  //輸出‘person1‘21     person2.emit(‘call2‘);  //沒有輸出22     person1.emit(‘call1‘);  //沒有輸出23     person2.emit(‘call2‘);  //輸出‘person2‘24 25 26     var Event = {27         //通過on介面監聽事件eventName28         //如果事件eventName被觸發,則執行callback回呼函數29         on:function(eventName, callback){30             //你的代碼31         },32         //觸發事件 eventName33         emit:function(eventName){34             //你的代碼35         }36     };

 

 

  • Object.assign(target, ...sources)  可以把任意多個的來源物件自身的可枚舉屬性拷貝給目標對象,然後返回目標對象。

 

 

這裡有篇解決的……但是沒看明白http://blog.daraw.cn/2016/08/02/javascript-event-emitter/

js:實現自訂事件對象介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.