3

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?

3
  • 5
    Don't do that. Either create your own objects or use a function. Read Maintainable JavaScript: Don’t modify objects you don’t own/ Commented Jan 26, 2015 at 13:57
  • You can take a look at this gist. Commented Jan 26, 2015 at 13:58
  • This looks horrible. This "subclass" of String is mutable, and its length is not even guaranteed to be equal to its length. Commented Jan 26, 2015 at 14:02

1 Answer 1

7

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

1 Comment

very nice dude, thumbs up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.