The only way to do this is to turn foo() into a function. Think of it as initializing the foo namespace for a particular string:
String.prototype.foo = function () { var str = String(this); var o = Object(this) o.bar = function () { console.log(str); }; return o; };
Then you can use:
"foobar".foo().bar(); // logs "foobar"
Or, if we rename foo and bar to something more exciting:
"Hello!".console().log(); // logs "Hello!"
Why is it so hard?
Each function is called with a specific context , which is the only object. Whether this is called using ab() or abcd() does not matter - the object immediately on the left of the function call is provided as its context. So the context for ab() is a , and the context for abcd() is c . This keyword refers to context. Since c is just an object (not a working function), it has no context and no concept of this , so this.this doesn't make sense.
Therefore, it is not possible to access the so-called "parent". Juan's answer provides a good conceptual explanation of why. However, if you want to get the namespace in prototype functions, you can do this by returning the extended object from foo .
Note that I also had to convert this to Object above. This is because you cannot attach properties to primitive values, such as strings. var str = "foo"; str.bar = 1 var str = "foo"; str.bar = 1 will work, but only because JS will automatically convert "foo" to an object. However, since str refers to a primitive rather than an automatically created object, the object is immediately discarded, and we lose the bar .
David tang
source share