js:实现自定义事件对象接口

网易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     //测试2
10     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接口监听事件eventName
28         //如果事件eventName被触发,则执行callback回调函数
29         on:function(eventName, callback){
30             //你的代码
31         },
32         //触发事件 eventName
33         emit:function(eventName){
34             //你的代码
35         }
36     };

 

 

  • Object.assign(target, ...sources)  可以把任意多个的源对象自身的可枚举属性拷贝给目标对象,然后返回目标对象。

 

 

这里有篇解决的……但是没看明白http://blog.daraw.cn/2016/08/02/javascript-event-emitter/

 

 

还是牛客高手多

 1         var Event = {
 2             on: function(eventName, callback){
 3                 this[eventName] = this[eventName] || new Array();
 4                 this[eventName].push(callback);
 5             },
 6 
 7             emit: function(eventName){
 8                 var params = arguments.length>1 ? Array.prototype.slice.call(arguments,1) :[];
 9                 if(this[eventName]){
10                     Array.prototype.forEach.call(this[eventName],function(arg){
11                         arg.apply(this,params);
12                     });
13                 }
14             }
15         }

以上的方法实现过程中,遇到一些问题……

  1) 一开始想茬了,以为this[eventName]可以写作this.eventName,然而输出结果总是不对。然后才想到,this.eventName等于是调用了名为'eventName’的属性,而不是把eventName代表的字符串传给this的属性。所以失败了。

  2)一开始以为Array.prototype.slice/forEach可以写作Array.方法名,但是会报错。所以应该是只能通过prototype调用call/apply

  3)一开始没有理解这道题的意思。其实指的是:Event中的on绑定事件,而emit执行事件。一开始以为触发事件的代码:Event.emit('test','hello world'); 是传入了两个参数,一次传入test,一次传入hello world。其实完全想错了……很明显,'test’是一个eventName,是在test绑定的事件里传入参数hello world.而之所以输出hello world与test,是因为test绑了两个事件,一个是有参数的输出参数,一个是没有参数的输出test。所以这里是事件绑定而非赋值。

  4)关于Object.assign(). 其定义是这样的:

Object.assign(target, ...sources)

Properties in the object will be overwritten by properties in the sources if they have the same key.  Later sources' properties will similarly overwrite earlier ones.  

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions, including their enumerability, into prototypesObject.getOwnPropertyDescriptor() and Object.defineProperty() should be used instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError will be raised, and the targetobject remains unchanged.

Note that Object.assign() does not throw on null or undefined source values.

  即:将来自一个或多个源对象中的值复制到一个目标对象。

    此函数返回目标对象。

    可枚举自有属性从源对象复制到目标对象。

    可使用此函数合并或克隆对象。

    null 或 undefined 源被视为空对象一样对待,不会对目标对象产生任何影响。

  【以下是我的渣翻译】这里意思是说:对象中的属性会被源中的属性覆盖,后面的属性会被前面的覆盖。

  这种方法只会从源对象中复制可枚举的和自己的属性到一个目标对象。然后返回目标对象。

  如果要复制属性定义,包括其可枚举性,应该使用Object.getOwnPrototypeDescriptor()和Object.defineProperty()

  5)牛客网上答题的大神更新了答案,把this复制给一个变量self, var self = this,然后其后的this都用self代替,是【考虑到了参数及this作用域的改进版本】。但是这里并不理解,既然在这个函数里,this和self都指向一样啊?为何要这么做呢?

    我大概明白了……在函数里调用this可能会引发各种奇怪的问题,因为this的指向并不一定总是你想要指的this。但是用self应该也不恰当,因为“You should avoid self as there is a window.self object and you could end up using that accidentally if you forget to declare your own self var”——应该避免self因为有一个window.self对象。所以这里我改成了that。于是代码写作:

 

 1         var Event = {
 2             on: function(eventName, callback){
 3                 if(!this[eventName]){
 4                     this[eventName] = [];
 5                 }
 6                 this[eventName].push(callback);
 7             },
 8             emit: function(eventName){
 9                 var that = this;
10                 var params = arguments.length>1 ? Array.prototype.slice.call(arguments,1) : [];
11                 if(that[eventName]){
12                     Array.prototype.forEach.call(that[eventName],function(arg){
13                         arg.apply(self,params);
14                     });
15                 }
16             }
17         }

 

posted on 2016-08-04 20:11  杠子  阅读(4369)  评论(0编辑  收藏  举报

导航