开发者

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.


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 () {}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜