Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing String in JavaScript

I have a string method String.prototype.splitName() that splits an author's name (a string) in first name(s) and a last name. The statement var name = authorName.splitname(); returns an object literal name with name.first = "..." and name.last = "..." (properties of name have string values).

Recently I was told that it is unwise to have splitName() as a method of the public String() class, but that I should make a private subclass of String and extend the subclass (instead of the public class) with my function. My question is: how do I perform subclassing for strings so that after I assign authorName to the new subclass name = authorName.splitname(); is still a valid statement? And how would I assign authorName to the new private subclass of String?

like image 492
P. Wormer Avatar asked Jul 06 '26 14:07

P. Wormer


1 Answers

Inspired by https://gist.github.com/NV/282770 I answer my own question. In the ECMAScript-5 code below I define an object class "StringClone". By (1) the class inherits all properties from the native class "String". An instance of "StringClone" is an object to which the methods of "String" cannot be applied without a trick. When a string method is applied, JavaScript invokes the methods "toString()" and/or "valueOf()". By overriding these methods in (2), the instance of class "StringClone" is made to behave like a string. Finally, the property "length" of an instance becomes read-only, which is why (3) is introduced.

// Define class StringClone
function StringClone(s) {
    this.value = s || '';
    Object.defineProperty(this, 'length', {get:
                function () { return this.value.length; }});    //(3)
};
StringClone.prototype = Object.create(String.prototype);        //(1)
StringClone.prototype.toString = StringClone.prototype.valueOf
                               = function(){return this.value}; //(2)

// Example, create instance author:
var author = new StringClone('John Doe');  
author.length;           // 8
author.toUpperCase();    // JOHN DOE

// Extend class with a trivial method
StringClone.prototype.splitName = function(){
     var name = {first: this.substr(0,4), last: this.substr(4) };
     return name;
}

author.splitName().first; // John
author.splitName().last;  // Doe
like image 73
P. Wormer Avatar answered Jul 08 '26 05:07

P. Wormer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!