Is it safe to attach a method to a String if you remove it after using it?

I just broke into the Node.js and CommonJS modules and I am trying to extend the String object without cluttering the rest of my application and providing a clean method.

I was wondering if it is possible to attach a method to a global String object and then at the bottom of the file, delete

it?

For example:

// hasCondition.js

String.prototype.has = function(regex) {
    return regex.test(this);
};
exports.removeMethod = function () {
    delete String.prototype.has;
};

      

...

// someFile.js

var has = require('./hasCondition');
console.log(  "foo bar baz".has(/baz/)  );
has.removeMethod();
console.log(  "foo bar baz".has(/baz/)  );

>>> true
>>> Object foo bar baz has no method 'has'

      

+3


source to share


2 answers


If you don't want to clutter up the String space, you can create a new object prototyped from String. Then assign this object to a method has

in its prototype. It will not be cast back to String.

This way you encapsulate this. Of course, you add another layer of indirection, but this is already a design pattern .

If you are concerned about what's has

stored somewhere later, it probably won't. Even if you create sub-objects from String with added method has

, when it is removed, just like from any inheritance.



An example of this (assuming the assertion is defined):

function Str1() {}
Str1.prototype = new String()
String.prototype.has = function(t) { /* code here */ }
var x = new Str1()
assert(x.has)

function Str2() {}
Str2.prototype = new Str1()

var y = new Str2()
assert(y.has)

delete String.prototype.has

assert(typeof x.has === "undefined")
assert(typeof y.has === "undefined")

      

+1


source


Consider this case: You create this module, it is very useful, so you host it on NPM and many people use it. Some of these users also thought that expanding the string object would be useful to them, and they also named one of their methods "has".

When they use your module, it overwrites its has method with yours. Don't worry when you clear up after yourself and remove the method you added. You know what comes next ... they're trying to use their method, and suddenly it's undefined!



If you call it something really obscure, it is unlikely that you will run into this, but this is not the best approach yet. It is generally best to try and keep your code as well as encapsulated within a module as much as possible and avoid leaks.

In this case, you may need to create your own string constructor that you can use and extend with custom methods for your heart content without fear of leaking your enhancements outside the module.

0


source







All Articles