Rakesh Juyal
Rakesh Juyal

Reputation: 36799

Using "this" keyword inside method of an object

Here is the 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 achieve 1st point via following code, but that seems very long way ( 2nd problem is still there ):

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?

Upvotes: 4

Views: 97

Answers (2)

CrossUI
CrossUI

Reputation: 144

In this scenario, 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();

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

You could have 2 different class like functions here:

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 a property of Fun in your Main:

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

or like:

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();

Upvotes: 3

Related Questions