How to create a function and call its methods without using new, similar to jQuery $?

6

The $ (dollar sign) of jQuery is a function , however you can access its methods as if it were an object through the "." . Could someone explain, in what way I could do this in a function func , for example?

In a more enlightening way, I intend to use func () as well as func.each () for example.

    
asked by anonymous 28.11.2017 / 12:53

2 answers

2

In JavaScript functions are special types of objects, and can have properties (including other functions) like any object:

function funcao(x) {
    console.log('função chamada');
}

funcao.propriedade = 10;
funcao.metodo = function() { console.log('método chamado') }

// Testes:
funcao();
console.log(funcao.propriedade);
funcao.metodo();

In jQuery, the thing is a bit more complex because all methods go in the prototype , the $ function is a constructor, and the library implements method-threading of the instances of this constructor. But in your case, perhaps the rice bean should be enough (please let me know if this is not enough).

    
28.11.2017 / 17:04
6

You can store a function in a variable and use it to perform internal functions through an object, this algorithm implements Javascript Module Pattern .

var $fn = function() {
  return {
    alertar: alertar
  }

  function alertar(message){
    alert(message);
  }
}();

$fn.alertar("teste")

You can also implement a function through prototype :

var $fn = function () {
    if (this instanceof $fn) 
        return this

    return new $fn;
};

$fn.prototype = {
    alertar: function (message) {
        alert(message);
    }
};

window.$ = $fn();
    
28.11.2017 / 13:23