Using the "this" keyword inside an object method

Here is a snippet of my code:

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};

main.prototype.fun = function(){
    console.log ( "I am Fun");
    /*
      1st Here this will refer to Object of `main`. 
      But I want someway to bind f1 to fun not to main
    */
    this.f1 = function(){
        console.log ( "Help!");   
        return this;
    };

    this.f2 = function(){
        console.log ( "Print");
        return this;
    };

    /*
      2nd. Here again this will refer to Object of `main`. 
      But I want to return object of fun.
    */
    return this;
}

Now I can reach the 1st point with the following code, but it seems very long (the second problem still exists):

main.prototype.fun.prototype.f1 = function(){
    console.log ( "Help FUN");
    return this;
};

main.prototype.fun.prototype.f2 = function(){
    console.log ( "Print FUN");
    return this;
};

How do you guys handle this scenario?

+4
source share
2 answers

Here you can have 2 different classes:

var Fun = function(){ };

Fun.prototype.f1 = function(){
  console.log ( "Help FUN");
  return this;
};
Fun.prototype.f2 = function(){
  console.log ( "Print FUN");
  return this;
};

Then define the property Funin Main:

var Main = function(){ };
Main.prototype.fun = new Fun();

or how:

var Main = function(){
  this.fun = new Fun();
};

Then you can use it like:

var main = new Main();

main.fun.f1().f2();

or

main.fun.f2().f1();
+3
source

In this case, you can use arguments.callee;

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};
main.prototype.fun = function(){
    console.log ( "I am Fun");
    var scope=arguments.callee;
    scope.f1 = function(){
        console.log ( "Help FUN");
        return scope;
    };
    scope.f2 = function(){
        console.log ( "Print FUN");
        return scope;
    };
    return scope;
}

// test it
var test1=new main();
test1.f();
var test2=test1.fun();
test2.f1();
test2.f2();

Or

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};
var fun=main.prototype.fun = function(){
    console.log ( "I am Fun");
    fun.f1 = function(){
        console.log ( "Help FUN");
        return fun;
    };
    fun.f2 = function(){
        console.log ( "Print FUN");
        return fun;
    };
    return fun;
}

// test it
var test1=new main();
test1.f();
var test2=test1.fun();
test2.f1();
test2.f2();
0
source

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


All Articles