How to create a Function and call your methods without using new, similar to jQuery’s $ ?

Asked

Viewed 554 times

6

The $ (jQuery dollar) is a Function, however it is possible to access its methods as if it were an object through the operator ".". Someone could explain, in what way I could do this in a Function func, for example?

function func

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

2 answers

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();
  • This way does not answer my question, because $fn is not a Function but an object. That is typeof $fn returns "Object" and not "Function" as typeof $

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 little more complex because all methods go in prototype, the function $ is a builder, and yet the library implements chaining of methods of the instances of that builder. But in your case maybe enough beans-with-rice above (warn if not enough).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.