Creating libraries with multiple executions like Jquery [duplicate]

2

I'm now starting to develop my own Javascript libraries. I already understand a bit how prototype works but I still do not understand how I can execute on the same request more than one method as jquery does ... EX:

//no jquery eu posso executar qualquer função em cascata assim
$('alguma coisa').metodo1().metodo2().metodo3();

//ou assim
$('alguma coisa').metodo1();
$('alguma coisa').metodo2();
$('alguma coisa').metodo3();

I would like to know how I can create a simple library so I can execute numerous methods at the same time as Jquery does ...

    
asked by anonymous 08.04.2016 / 03:31

1 answer

3

Just at the end of the method you return the object itself (return this):

Example:

var Numero = function(num){
 this.num = num;
 this.valueOf = function(){
    return this.num;
 }
 this.maisUm = function(){
    this.num += 1;
    return this;
  }
  this.maisDois = function(){
    this.num += 2;
    return this;
  }
  return this;
}
var meuNum = new Numero(1);
alert(meuNum.maisUm().maisDois().maisUm() + 1); //1 + 1 + 2 + 1 + 1 = 6

Javascript is a very flexible language, when I use Numero = function(num){ ... } I'm creating a class Number and indicating that function(num){...} is your constructor method. Within this method, I can use the this properties to set the properties and methods of the class.

    
08.04.2016 / 03:45