Last active
December 17, 2015 17:58
-
-
Save rishabhmhjn/5649357 to your computer and use it in GitHub Desktop.
Encapsulating Array Object to add a custom method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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