How to "concatenate" Javascript functions?

Asked

Viewed 504 times

3

How does jQuery lib? Example:

$(element). text('my text');

I want to know how to do a function like text() in pure Javascript, just to learn the theory. I want to know how the html element is passed as a parameter to the function text(), that makes the innerText in the same element encapsulated by the function $().

I want to know how the function text() recognizes in which element it should add the text only being joined to the $() with a point (.)?

I only use jQuery, but my will is to learn pure JS in depth.

  • 4

    http://answall.com/q/81128/129, http://answall.com/questions/14968/como-crea-um-plugin-para-a-fun%C3%A7%C3%a3o-do-jquery/14975? s=1|1.1881#14975, http://answall.com/a/500/129,

  • 2

    I have the impression that this question has more to do with implementation than with method chaining, which is what you have in the other question. It would be good for the author to read the post indicated, and [Edit] the post here explaining better the points of interest that there do not charge, qq way.

1 answer

4


This is called interface Fluent or method chaining. Or at least it’s a similar way.

The basic technique is to return the very object being manipulated, the this. The return something that can be manipulated by another function that expects an object.

You can see the source code of the example you used. And the selector source code (will accompany us links the rest of the code). In the selector you will see that it returns this which will be used as argument for the function text().

If you want to create functions that communicate specifically with jQuery you have to follow some protocols. There are some links in Sergio’s comment (in question) which show how.

English article on the subject.

  • In addition, jQuery stores the selected elements in the reference itself, sequentially, for example: this[0] = algumElementoDOMWindowEtc, this[1] = outroElementoEtc (Is it correct to say that? ), exactly like a collection, instantiated by the jQuery interface.

Browser other questions tagged

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