RaduC
RaduC

Reputation: 33

Using "dot" inside a prototype name in JavaScript

Lets say I have this class:

function classA(n){
    this.name = n
}

classA.prototype.getName = function(){
    return this.name
}

var x = new classA('john')
console.log(x.getName())

My question is: can I group multiple methods inside a namespace? So I would like to do that:

var x = new classA('john')
console.log(x.CONSTANT.getName())

So I would like to call some methods as x.someMethod() and others as x.CONSTANT.otherMethod()

PS: I'm looking for a cross-browser method. Bind is not working in Safari and IE9.

Upvotes: 3

Views: 338

Answers (4)

vdegenne
vdegenne

Reputation: 13270

As far as I know a constant is just a property and it can't contain methods, you need to separate your objects and use methods to have the same effect:

function A (id) {

    this.id = id;
    this.showId = function () { return this.id; }
};

function B (a) {

    this.a = a;
    this.getA = function () { return this.a; }
}

var a = new A(12);
var b = new B(a);

b.getA().showId();

edit: You can use a literal object as follow

function B (id) {

  this.id = id;
  this.CONSTANT = { otherMethod: function () { alert("..."); } };
  someMethod = function () { return this.id; }
}

but the literal CONSTANT object can't access B-object methods,

Consider the @kirilloid post to round this.

Upvotes: 1

kirilloid
kirilloid

Reputation: 14304

You can do it, for example, via bind. Google es5 shim for implementation of bind in browsers, which don't support it natively.

function MyClass(name) {
   this.name = name;
   this.CONSTANT.otherMethod = this.CONSTANT.otherMethod.bind(this);
}
MyClass.prototype.CONSTANT = {
   otherMethod: function() {
        alert(this.name);
   }
};

Upvotes: 3

freakish
freakish

Reputation: 56467

You can use getters/setters (read this article) to achieve this. For example you may define it like this:

classA.prototype.__defineGetter__('CONSTANT', function() {
    var that = this;
    return {
        getName: function() {
            return that.name;
        }
    };
});

Note that holding reference to the object. It will work now

x = new classA('test');
x.CONSTANT.getName();
// result - test

Upvotes: -1

djd
djd

Reputation: 5178

You can, but you have to be careful because it won't act like you think it will. The this for the method will be the namespace, not the root object. For example, in x.CONSTANT.getName(), the this object will be x.CONSTANT, and not x.

Here's some sample code which kinda does what you ask (or in jsfiddle):

function MyClass() {}

MyClass.prototype.CONSTANT = {
    getName: function() {
        alert('Foo');
    }
};


var c = new MyClass();
c.CONSTANT.getName();

To make sure the this is right, you need to do much more.

Upvotes: 0

Related Questions