call(‘me’); //weird

The Case : When a rookie corrupts my configuration in the Global Namespace

So, I was working with Namespaces. I was panicking over a situation when my configurations (set into the global namespace) could be overridden/deleted by any rookie who doesn’t use pipes e.g.

//my global configurations
(function() {
  this.myGlobalConfig = { ... };
  api = {
    init : fn.init.apply(this)
}.apply( Namespace || {} ) );
//after many lines of code, if the rookie writes
var Namespace = { ... }; //rookie missed the pipes here

The Case : When a rookie creates a global variable with the same name as the namespace

So, we let our rookie write anything. What the rook does is interesting:

var Namespace = 10; //say a number

Now, the question is: Will my module still work?
The answer is : Yes, except the APIs exposed to public.

Here is a hint why your module will still work without throwing any errors:

function foo () {
  return typeof this
}{});      //"object";       //"object""oh no"); //"object"

foo.apply({});      //"object"
foo.apply(1);       //"object"
foo.apply("oh no"); //"object"


Javascript implicitly converts any primitive data type to its corresponding Object type when you use call or apply on it. To verify, you can do a typeof check inside the class (function) name.

Here is a little test to prove this:

function foo () {
  console.log(this instanceof Number , "Number");
  console.log(this instanceof String , "String");
  console.log(this instanceof Array , "Array");
  console.log(this instanceof Object , "Object");
  return typeof this
// false "Number"
// false "String"
// false "Array"
// true "Object"
// "object";
// true "Number"
// false "String"
// false "Array"
// true "Object"
// "object""oh no");
foo.apply("oh no");
// false "Number"
// true "String"
// false "Array"
// true "Object"
// "object"

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s