Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new data type in JavaScript

Tags:

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.

like image 415
tqwer Avatar asked Dec 11 '10 09:12

tqwer


2 Answers

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 () {}
like image 148
dsas Avatar answered Sep 29 '22 01:09

dsas


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

like image 39
Daveo Avatar answered Sep 29 '22 00:09

Daveo