Extending Array.prototype in Node.js, from a require'd file

后端 未结 2 408
梦谈多话
梦谈多话 2021-01-06 03:07

I have the following saved in test.js. It successfully extends Array in the browser, but it doesn\'t seem to work with node and require. Can someone explain what\'s wrong

2条回答
  •  一生所求
    2021-01-06 03:24

    You can create a file which includes your extensions:

    array.extensions.js

    if(!Array.prototype.Last){
        Array.prototype.Last = function(){
            return this.slice(-1)[0];
        }
    }
    
    if(!Array.prototype.First){
        Array.prototype.First = function(){
            return this[0];
        }
    }
    

    then include this file to your startup file.

    app.js:

    require('{path}/array.extensions');
    var express = require('express');
    /* rest of your code */
    

    referring this file once on startup is enough to use...

提交回复
热议问题