简体   繁体   中英

Change Array.prototype in ecmascript (javascript)

I am working on an app using node_webkit combining HTML, CSS and JS. In one part of my app I want to update the Array.prototype so that I can access the last element of an array easily. The code for that is:

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
}

If I run only the js-file that works fine and as expected. If I include that js-file into an HTML document it seems that the prototype of the array stays unchanged and I get the error:

data.last is not a function

Do I have to change something so that I can run my code normally from an HTML file or does that not work at all and I have to take the long way around and access each array with array[array.length - 1]?

The HTML code I use to include the script is:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../CSS/Cocktails.css">
    <title>Cocktails</title>
    <script type="text/javascript" src="../JavaScript/Cocktail.js"></script>
  </head>
  <body>
  /* some elements, that don't use the script yet */
  </body>
</html>

It sounds like you're not calling the function, you'd want to call it like data.last() where data is some array that you've declared. Here's a JSFiddle of it in action.

In ES5 you need to use defineProperties in order to modify the Array prototype in an enumberable way:

Following should work,

Object.defineProperties(Array.prototype, 
       { last: { value: function() { return this[this.length - 1]; } } });

More information at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

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