Create a new data type in JavaScript

I want to extend the JavaScript data type and assign it to a new data type.

for example:
I want to create an IP address data type ( object), it has all the type properties String, but I don't know how to copy all the class properties Stringto IPclass.

+3
source share
2 answers

As far as I understand, you just copied its prototype. Note that various structures have ways to extend and extend javascript classes, which may be better. I have not tested this

var IPAddress = function() {};

// inherit from String
IPAddress.prototype = new String;
IPAdress.prototype.getFoo = new function () {}
+5
source

You can try something like this:

test = function() {
    alert('hello');
};

String.prototype.test = test ;
var s = 'sdsd';

s.test();
alert(s);

There are 1000 ways to do inheritance in JS

http://www.webreference.com/js/column79/4.html

http://www.webreference.com/js/column79/3.html

0

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


All Articles