Created
January 21, 2010 12:41
-
-
Save NV/282770 to your computer and use it in GitHub Desktop.
JavaScript String subclassing example. Based on http://webreflection.blogspot.com/2008/10/subclassing-javascript-native-string.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Markdown(value) { | |
this.value = value || ''; | |
this.length = this.value.length; | |
}; | |
Markdown.prototype = new String; | |
// Instance methods | |
Markdown.prototype.toString = Markdown.prototype.valueOf = function(){return this.value}; | |
Markdown.prototype.toHTML = function(){return Markdown.decode(this)}; | |
// Static methods | |
Markdown.decode = function(){}; | |
// Example: | |
m = new Markdown('*italic*'); | |
m.toHTML(); // '<i>italic</i>' | |
Markdown.decode('*italic*'); // '<i>italic</i>' |
I'm doubly confused by: "Markdown.decode = function(){};" --a function without arguments.
In the first place it is called with the parameter "this". In the second place decode() is not a native String method.
Presumably the reader is expected to write "decode()" him/herself and in the body convert "arguments[0].value" to HTML?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you have access to ES5, this would be better (replacing line 3):
You then get: