Skip to content

Instantly share code, notes, and snippets.

@dr-dimitru
Last active August 29, 2015 14:07
Show Gist options
  • Save dr-dimitru/dee5a5047ae3129f106e to your computer and use it in GitHub Desktop.
Save dr-dimitru/dee5a5047ae3129f106e to your computer and use it in GitHub Desktop.
Clone (a.k.a. create singleton) for String object
/*jshint strict:false */
/*
* @function
* @namespace String.prototype
* @name clone
*
* @description Clone (a.k.a. create singleton) of String object
* This method allows to resolve issue with variable's referencing
* See performance here: http://jsperf.com/clone-create-singleton-for-string-object
*
* @param {boolean} asObject - If true returns String object, if false returns literal
*
* @example
* var str = new String('abc');
* var str2 - str.clone();
* str = new String('cde');
* console.log(str2); //-> 'abc'
*/
Object.defineProperty(String.prototype, 'clone', {
value: function(asObject){ return (asObject) ? new String(this.toString()) : (new String(this.toString())).toString(); }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment