'Create new data type in JavaScript
I want to extend a data type of JavaScript and assign it to new data type.
E.g:
I want build a IP address data type (object),it have all properties of String type, but I do not know how to copy all the properties of the String class to IPclass.
Solution 1:[1]
As far as I understand you just copy it's prototype. Note that the various frameworks have ways to extend and augment javascript classes that may be better. I have not actually tested this
var IPAddress = function() {};
// inherit from String
IPAddress.prototype = new String;
IPAdress.prototype.getFoo = new function () {}
Solution 2:[2]
You can try something like this:
test = function() {
alert('hello');
};
String.prototype.test = test ;
var s = 'sdsd';
s.test();
alert(s);
There is like a 1000 ways to do inheritance in JS
Solution 3:[3]
var aType = function() {}
aType.prototype = new String
// We can create a simple type using the code above.
// Use new aType() to use that type.
aType.prototype.hello = function(text) {
return {
"a": this,
"b": text
}
}
// And use the code above to create a prototype that goes into the type we created by default.
var newaType = new aType()
console.log(newaType.hello())
// Create a variable called newaType and put that
// This code is a simple code that prints the value of executing its prototype hello to the console.
FYI, I'm not American, so I used a translation. Please understand if my writing is wrong :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dsas |
| Solution 2 | Daveo |
| Solution 3 |
