Skip to content

Instantly share code, notes, and snippets.

@rishabhmhjn
Last active December 17, 2015 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rishabhmhjn/5649357 to your computer and use it in GitHub Desktop.
Save rishabhmhjn/5649357 to your computer and use it in GitHub Desktop.
Encapsulating Array Object to add a custom method
var MyArray = function() { return this; } ;
MyArray.prototype = new Array();
MyArray.prototype.constructor = MyArray; // http://stackoverflow.com/a/10430875/842214
Object.defineProperty(MyArray.prototype, 'myLast', (function () {
return {
configurable : true,
enumerable : true,
get : function () {
return this[this.length - 1];
},
set : function (val) {
this.push(val);
}
};
})());
var testMyArray = new MyArray();
console.log(testMyArray); // []
console.log(testMyArray.myLast); // undefined
testMyArray.myLast = 1;
console.log(testMyArray.myLast); // 1
testMyArray.myLast = 2;
console.log(testMyArray.myLast); // 2
testMyArray.pop();
console.log(testMyArray.myLast); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment