I've been trying to understand inheritance in Javascript and so far I've read many sites about that (including javascript.info and Crockford's Javascript Good parts) - yet I can't seem to understand something as simple as Array inheritance.
Maybe if I demonstrate with an example, somebody can correct me and teach me what I'm getting wrong.
function ExtendedArray() {
Array.call(this, arguments);
this.test = function () {
return 'something';
}
}
//I think this is the most standard way to extend a class?
ExtendedArray.prototype = [];
ExtendedArray.prototype.constructor = ExtendedArray;
$scope = {};
$scope.arr = new Array(1, 2, 3);
$scope.concatArr = [].concat($scope.arr);
$scope.x = new ExtendedArray(1, 2, 3); //empty | instanceof Array = true
$scope.concatX = [].concat($scope.x); //empty
$scope.y = new ExtendedArray(); //instanceof Array = true
$scope.y.push(1, 2, 3); //works - elements are added!
$scope.concatY = [].concat($scope.y); //concats it like a object
Here is a JS-Fiddle for the same:
http://jsfiddle.net/superasn/pq2j139c/
Some questions:
- How do I fix this code so that
ExtendedArray
behaves as Array? - As you can see
$scope.x
is empty. Why is the constructor not working? - The
push
functions works!? But thenconcat
fails? How to makeconcat
work? - I see there are some libraries to extend Classes, is that a better approach to JS inheritance?
Your advise is appreciated!