Is it possible to organize prototype methods of an object into namespaces?

I am trying to create a specific syntax template in JavaScript. Essentially, the requirement is to extend prototypes of native JavaScript objects with new methods and organize these methods in namespaces. The result I'm looking for can be summarized as:

String.prototype.foo = {
    bar: function() { return this.toUpperCase(); } //Fails because "this" is foo, not it parent string
};
'test'.foo.bar(); //should return 'TEST'

I know that there are other ways to achieve similar results, but I would prefer the syntax to be higher, although I am almost 80% sure that this is not so.

I tried a dozen different ways to build this, but I can't find a way to reach the string like "this" inside bar (). I believe the problem is that since foo is an object and does not have executable code, the compiler cannot pass the owner of β€œthis” to it from there to the child method, but I wondered if there was some obscure technique for walking around Does the parent chain exist that I don't know about? The next best thing might be "test..foo (). Bar (), which I have not tried yet, but will most likely work.

+4
source share
3 answers

Of course, here you go:

Object.defineProperty(String.prototype,"foo", {
   get: function(){ 
        return { 
            bar: function(){ return this.toUpperCase() }.bind(this)
        }
   },
   enumerable: false, // don't show in for.. in loop
   configuratble: true,
});

"hello".foo.bar(); // "HELLO"

A few notes:

+4

, , :

String.prototype.foo = function(){
     var self = this;
     return {
         bar: function() { return self.toUpperCase(); }
     };
}

'test'.foo().bar()
0

Hi here is a solution with function

String.prototype.foo = function(){
    var that = this;
    return{
        bar:function(){
            return that.toUpperCase()
        }
    }
}

'test'.foo().bar();

I think the solution with the object does not exist. Please note: 1 object can exist in many "parents" to determine which one you need.

0
source

Source: https://habr.com/ru/post/1529506/


All Articles