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?
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
http://ajaxian.com/archives/another-trick-to-allow-array-subclasses
http://dean.edwards.name/weblog/2006/11/hooray/
, . length . , . , length . , .
, :
console.log(x[4]);
, , .
javascript, Array . , , , "" .
Array , , . , , , .
, , , , . , . , , , . , .
, "", - "Array", "Array-Like", , "", "", Collection, []. , (.. myArray["foo"] = "bar"), , .
[]
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();
Source: https://habr.com/ru/post/1755744/More articles:How to make tab key press work with win32 window, which is not a dialog - c ++Partially downloaded javascript file - nginxWhat dialect of LISP is "Little Lispper" [3rd Edn]? (at the time) - lispPlay! + Siena + GAE + JUnit - javaParsing Analyzer - c #A few questions about DLR - c #Does the Process.Start parameter containing spaces have problems with XP? - c #Как передать большой Zip файл (50 МБ) с помощью службы WCF через SOAP любому клиенту? - c#asp.net: link to the page relative to the root in normal html server-side controls - urlConverting types from string to custom type - c #All Articles