Basic Javascript Guide
Overview
Functions on Objects
let obj = {
add:function(a,b){
return a+b;
}
};
let sum = obj.add(1,3);
Try it!
Method Chaining
The ability to put functions on objects creates a nice way execute multiple functions within a single line.
Consider the following object.
let obj = {
test:function(a,b){
return {
test2:function(){
return 'hello'
}
};
}
};
The object has a function set on it name "test". This function returns a different object,
also with a function on it, this time named "test2". Now, consider the following code:
let text = obj.test().test2();
let text2 = obj
.test()
.test2();
Try it!
This code calls the method "test" on obj. However, it then calls "test2" on the object that is returned.
That is, the code is evaluated by replacing the expression "obj.test()" with the object that it resolves to,
and then the function test2 is called. The second line of code shows a common way to format these chained calls.
Because Javascript ignores the white space, these two function calls are the same.