简体   繁体   中英

meaning of push: function in javascript

What is the meaning of return { push:function ..... in below code snippet. When I googled I found that push() method adds new items to the end of an array, and returns the new length. So I am not sure what is push:. It seems to be some kind of syntax. Can someone please explain me.

 function(notificationsArchive) { var MAX_LEN = 10; var notifications = []; return { push: function(notification) { var notificationToArchive; var newLen = notifications.unshift(notification); //push method can rely on the closure scope now! if (newLen > MAX_LEN) { notificationToArchive = this.notifications.pop(); notificationsArchive.archive(notificationToArchive); } }, // other methods of the NotificationsService }; 

The method push you are referencing has nothing to do with push with Arrays, it is a public method exposed by the module pattern. It only exposes methods and properties that the author of the code wants you to be able to call/set. It hides the variables MAX_LEN and notifications so they can not be changed from outside.

References on OO Module patterns:

 function(notificationsArchive) { var MAX_LEN = 10; var notifications = []; return { push: function(notification) { var notificationToArchive; var newLen = notifications.unshift(notification); //push method can rely on the closure scope now! if (newLen > MAX_LEN) { notificationToArchive = this.notifications.pop(); notificationsArchive.archive(notificationToArchive); } }, // other methods of the NotificationsService }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM