I'm a beginner at javascript
I would like to inherit the Array class of javascript and create a new class of my own class.Previously, I inherited ArrayList in Java and created it, so I wrote the following code with reference to automatic conversion in jsweet.I created a method unnest that eliminates any nesting in the list.
var SuperArray=(function(){
functionSuperArray(c){
if(((c!=null&&(c instance of Array))||c===null)){
var__args = Array.prototype.slice.call(arguments);
}
else if(c===undefined) {
var__args = Array.prototype.slice.call(arguments);
}
else
US>throw new Error ('invalid overload');
}
SuperArray.prototype = Object.create (SuperArray.prototype, {value:{constructor:SuperArray}});
SuperArray.prototype.unnest=function(){
varlist=(function(){var_o=new SuperArray();_o.__delegate=[];return_o;})());
for(vari=0;i<this.__delegate.length;i++){
varo=this.__delegate[i];
if(o!=null&o instance of SuperArray) {
/* addAll*/(function(l1,l2) {return l1.push.apply(l1,l2);}) (list.__delegate,o.unnest());
}
else{
/* add*/(list.__delegate.push(o)>0);
}
}
;
return list;
};
return SuperArray;
}());
Chrome generated the error Uncaught TypeError: Cannot read property 'length' of undefined when creating an object for the SuperArray class.Since SuperArray inherits Array, I thought I could use the length parameter...
By the way, you can list.length to SuperArray object list, but list.unnest().length will cause the above error.
I studied inheritance and protocol, but there are many things I don't understand.It seems that there are many things that I misunderstood, but it would be very helpful if you could tell me.Thank you for your cooperation.
Additional information below
8/14 15:50
_delegate and constructor are marked as jsweet.I don't really want to throw a whole ball, but there are many things I don't understand even if I look into it, so I would appreciate it if you could tell me about a website that I can refer to.
SuperArray has not succeeded to Array
-SuperArray.prototype=Object.create(SuperArray.prototype, {value:{constructor:SuperArray}});
+ SuperArray.prototype = Object.create (Array.prototype, {value:{constructor:SuperArray}});
I think it's going to work in
When inheriting complex built-in objects such as Array and RegExp, it is preferable to inherit using the extends
keyword rather than using the Object.create
to inherit them.
class SuperArray extensions Array {}
var superArray1 = new SuperArray(1,2,3);
console.info (...superArray1); // 1, 2, 3
superArray1.length = 0;
console.info(...superArray1); // undefined
Array features that manipulate index properties when manipulating length properties are also inherited
If the environment is not available after ES6, I think it would be better to convert it to ES5 in Babel.
There is also an online repl, so why don't you try it?
© 2024 OneMinuteCode. All rights reserved.