In JavaScript, how do I access an object inherited from Array using the [] operator?

I have a situation where I need to create a new JavaScript object that is inherited from Array. I am using the following code:

// Create constructor function.
var SpecialArray = function () {};

// Create intermediate function to create closure upon Array prototype.
// This prevents littering of native Array prototype.
var ISpecialArray = function () {};
ISpecialArray.prototype = Array.prototype;
SpecialArray.prototype = new ISpecialArray();
SpecialArray.prototype.constructor = SpecialArray;


// Use Array push() method to add two elements to the prototype itself.
SpecialArray.prototype.push('pushed proto 0', 'pushed proto 1');

// Use [] operator to add item to 4th position
SpecialArray.prototype[4] = 'direct [] proto to 4';

// Create new instance of Special Array
var x = new SpecialArray();

// Directly add items to this new instance.
x.push('pushed directly on X');
x[9] = 'direct [] to 9'

console.log(x, 'length: ' + x.length);

Interestingly enough, the operation [] seems useless, and the console output:

["pushed proto 0", "pushed proto 1", "pushed directly on X"] length: 3

What am I missing here?

+3
source share
3 answers

It is not possible to subclass the Array class and use t in this way. The best solution for you is to expand the array class and use it as is. There are two other options that I don't like, but they exist

+4

, . length . , . , length . , .

, :

console.log(x[4]);

, , .

javascript, Array . , , , "" .

Array , , . , , , .

, , , , . , . , , , . , .

+3

, "", - "Array", "Array-Like", , "", "", Collection, []. , (.. myArray["foo"] = "bar"), , .

:

http://codepen.io/dustinpoissant/pen/AXbjxm?editors=0011

var MySubArray = function(){
  Collection.apply(this, arguments);
  this.myCustomMethod = function(){
    console.log("The second item is "+this[1]);
  };
};
MySubArray.prototype = Object.create(Collection.prototype);

var msa = new MySubArray("Hello", "World");
msa[2] = "Third Item";
console.log(msa);
msa.myCustomMethod();
0

Source: https://habr.com/ru/post/1755744/


All Articles