4

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.

4
  • 1
    Is there a reason you can't simply extend the String type using its prototype? Commented Dec 11, 2010 at 9:15
  • 1
    Look for Inheritance in Javascript on web search. Commented Dec 11, 2010 at 9:17
  • 1
    @Oded: I think he is asking how precisely to formulate "extending using prototypes". Commented Dec 11, 2010 at 9:27
  • @tqwer Careful, in Javascript you cannot create data types, javascript is not an oop language, when you instance an object (e.g let obj = new Smth()), you create a " structure of type Object around a structure called prototype(==Smth.prototype in my example) ". Commented Apr 10, 2019 at 17:18

3 Answers 3

8

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 () {}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

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

Comments

0
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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.