How Does Basic Object/Function Chaining Work in JavaScript

How does basic object/function chaining work in javascript?

In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:

var gmap = function() {
this.add = function() {
alert('add');
return this;
}

this.del = function() {
alert('delete');
return this;
}

if (this instanceof gmap) {
return this.gmap;
} else {
return new gmap();
}
}
var test = new gmap();
test.add().del();

By assigning the

new gmap();
to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".

In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.

Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be.

How do object or method chaining work in jQuery?

If you have an object with certain methods, if each method returns an object with methods, you can simply call a method from the object returned.

var obj = {   // every method returns obj---------v
first: function() { alert('first'); return obj; },
second: function() { alert('second'); return obj; },
third: function() { alert('third'); return obj; }
}

obj.first().second().third();

DEMO: http://jsfiddle.net/5kkCh/

How to create chaining of objects in js

You can do it using class style too

class Chainable{

init(num){
this.total = num;
return this;
}

add(num){
this.total += num;
return this;
}
}

using it like so

var c = new Chainable();
c.init(1).add(1);

how to do method chaining in object oriented Javascript?

push returns the new length of the array, which is not what you want. Return the instance (this) instead:

var expertSurfLevel = []var noviceSurfLevel = []var IntermediateSurfLevel = []
class SurfSpots { constructor() { this.windSpeed = [-1.3, 1.34, 2.51, -2.55], this.totalWindSpeed = 0 } expert(totalWindSpeed) { if (totalWindSpeed.some(num => num < 0) === false) { expertSurfLevel.push(this.coords); } return this; } novice(totalWindSpeed) { if (totalWindSpeed >= -5 || totalWindSpeed <= 15) { noviceSurfLevel.push(this.coords); } return this; } intermediate(totalWindSpeed) { if (totalWindSpeed >= 5 || totalWindSpeed <= 20) { IntermediateSurfLevel.push(this.coords); } return this; }}
var surfSpot = new SurfSpots();surfSpot .expert(surfSpot.windSpeed) .novice(surfSpot.totalWindSpeed) .intermediate(surfSpot.totalWindSpeed)console.log("surfSpot", surfSpot)

Basic method chaining with DOM elements

As already explained in a comment this is not the selected element. With minimal refactoring in your code what you can do is adding a new element property to your object, setting it in getId and using that element in text. For instance:

'use strict'let chain = {  element: null,  getId(id) {    this.element = document.getElementById(id);    return this  },  text(content) {    this.element.textContent = content;    return this;  }}window.addEventListener('load', function() {  let dummy = chain.getId('dummy').text('works');})
<div id='dummy'></div>

create object chaining using loop

I think looking into functional programming will help you here.

I used a pipe function from the internet link below but you could use lodash/Ramda/underscore or whatever your fav util library is.

the two main concepts I'm using here is currying and piping.

What is 'Currying'? Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments
we are also making use of curring which is returning a function from another function to compose new functions.

https://medium.com/@venomnert/pipe-function-in-javascript-8a22097a538e A pipe function takes an n sequence of operations; in which each operation takes an argument; process it; and gives the processed output as an input for the next operation in the sequence. The result of a pipe function is a function that is a bundled up version of the sequence of operations.

what we're doing here is taking an array, creating a new array of functions we want to apply to a value.

So we want to do a load of joins on a db.

join => con => con.innerJoin(join);

is taking a value i.e "table1" and returning a function that takes a db connection which calls the join and returns for the next one.

const joins = toJoin.map(join => con => con.innerJoin(join));
and this creates are array of functions to pass to pipe.

const db = ({  select: function (field) {    console.log('select', field)    return db  },  from: function (table) {    console.log('from', table)    return db;  },  innerJoin: function (join) {    console.log('innerJoin', join)    return db;  }});
const _pipe = (a, b) => (arg) => b(a(arg));const pipe = (args) => [].slice.apply(args).reduce(_pipe);
function joinInnerMultiple(table, fields, toJoin) { const joins = toJoin.map(join => con => con.innerJoin(join));
return pipe(joins)(db.select(fields).from(table)); }

joinInnerMultiple("User", "uuid", ["table1", "table2", "table3", "table4", "table5"])

Method Chaining in a Javascript Class

if you were to return the ball (in the case of your example Ball2) object at the end of each of your functions it will work. you can do this by calling "return this" at the end of each function to chain methods.

you can take a look at the wikipedia java example to see how they implement it:
https://en.wikipedia.org/wiki/Method_chaining



Related Topics



Leave a reply



Submit