How beautiful it is to have plenty of actions in just one line. $(‘p’).text(“This is an example of chaining!!”).addClass(“paragraph-design”); This “chaining thing” uses the “this” keyword to get method chaining to work. But, what’s “this”? In JavaScript “this” always refers to the “owner” of the function we’re executing, or rather, to the object that a function is a method of. Quirksmode.org Let’s get into action: var Person = function(name, age) { this.name = name; this.age = age; }; Person.prototype.getName = function() { console.log("Your name is: ", this.name); return this; }; Person.prototype.isAdult = function() { var isAdult = this.age >= 18 ? 'Yes' : 'No'; console.log("Is an adult: ", isAdult); return this; }; Person.prototype.setNationality = function (nationality) { this.nationality = nationality; return this; }; Person.prototype.getInfo = function() { console.log('Your name is ', this.name, ' and you are', this.nationality); return this; }; var p = new Person("Garou", 36); p.getName().isAdult().setNationality("Mexican").getInfo(); This class was created by using the prototypical pattern. JavaScript offers different ways to create objects, and with ecma6 the keyword class was introduced. As mentioned above, the secret behind the chaining idea is to use the “return this” in every method we want to use. Tu run this sample with node, just type in your console. >> node chaining-example.js Here, you create an object called p which is an instance of Person. And then, you call your methods in just one line. var p = new Person("Hugo", 45); p.getName().isAdult().setNationality("Québécois").getInfo(); Also, you can use it this way: New Person("Roch Voisine",54).getName().isAdult().setNationality("Québécois").getInfo(); This was just a simple way to implement chaining. It includes some other concepts like objects, prototypes, functions, instances, etc. Some helpful bibliography I personally like is: 1. You Don't Know JS by Kyle Simpson 2. EcmaScript for Humans by Deepak Grover and Hanu Prateek Kunduru 3. Beautiful JavaScript by Anton Kovalyov
0 Comments
Leave a Reply. |