Return variable or variable.function

Hi everyone,

I was wondering how i could run something like this :


I have been trying some solutions on my own but i cant find how to implement functions.

here is my basic idea, if anyone has a solution / a theory, you’re welcome to share :smiley:

t = (function(){
		var x = "test";
    var _x = function(){
    	return x || -1;
    		x : function(){return _x();}()

What is it that you’re trying to do?

Well for instance i would like to access my variable by writing t.x (which would return the variable x)
But i would like to be able to apply transformations on the variable for instance :
t.x.base64() or t.x.asTime()
Which would return x in a certain format !

This looks like you want to extend the native objects.

That might be the solution !
Now i must say i am not used to extending the native objects. How would you do it in this case ? Could you provide me an example ?

EDIT : Actually after looking into it, i’m not convinced this is the right way of doing things. Yes we might end up with the desired result, but it doesn’t feel right.

yupp, extending native objects should only be done with great care.

the only other way I see is wrapping your value into its own object (similarly to what jQuery does with DOM objects) and put the methods there. This means that you can only used wrapped values (but that should be not that of a problem). And you have to make sure that you don’t wrap objects twice (again, see jQuery as example).

With the ES6 class and super keywords, you can actually extend (as in inherit from) native objects without touching the original’s prototype:

class SuperString extends String {
  constructor (value) {

  toBase64 () {
    return btoa(this)

const x = new SuperString('foo')

console.log(x)            // "foo"
console.log(x.toBase64()) // "Zm9v"

I don’t think calling the parent constructor like this is directly possible w/o super though… not without some deeper magic at any rate.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.