Javascript Data Type How to - Extend Array to add change listener








Question

We would like to know how to extend Array to add change listener.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from w  w w. j  a  v  a2s  . c  om-->
var MyArray = function() {
    var arr = [];
    arr.push = function() {
        console.log("PUSHING", arguments);
        return Array.prototype.push.apply(this, arguments);
    }
    return arr;
};
var arr = new MyArray;
arr.push(12, 3, 45);
console.log(arr, arr[2]);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: