Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 576
RaduC Avatar asked Apr 08 '26 08:04

RaduC


1 Answers

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);
   }
};
like image 161
kirilloid Avatar answered Apr 09 '26 21:04

kirilloid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!