0

I don't want to pollute the prototype of objects with all my library's methods. I want to hide them inside a __namespace property.


When you try to access an object property, if it is undefined, it will look up the prototype chain like so

a.c -> a.prototype.c -> a.prototype.prototype.c ..

I would like to achieve

a.__namespace.c -> a.prototype.__namespace.c, a.prototype.prototype.__namespace.c ...

Exemple :

function A(){};
A.prototype.__namespace = {};
A.prototype.c = 2; // normal 
A.prototype.__namespace.c = 2; // inside namespace

var a = new A();
a.__namespace = {};
console.log(a.c) // prints 2
console.log(a.__namespace.c); //undefined. Would like to print 2.

Is there a javascript functionality that allows this other than creating it like :

function NameSpace(){}
NameSpace.prototype.c = 3;

var a = new A();
a.__namespace = new NameSpace();
console.log(a.__namespace);

Check this fiddle.

Ludovic C
  • 2,855
  • 20
  • 40

1 Answers1

0

I just Fiddled around and came up with that. I'm not 100% sure if it's what you are intending.

Essentially I am storing the prototyped functions in a single property of the prototype.

SomeObject.prototype.someNamespace = Object.create(SomeOtherObject.prototype);

Of course, the SomeOtherObject will have to have a polluted prototype.

ATTEMPT 2

I tried again. Is this what you are intending?

JosephGarrone
  • 4,081
  • 3
  • 38
  • 61