1.

What should be changed in the below code that it prints x, y and z?

Answer»

The output right now will be as below, as the method CHAINING is not understood by the compiler.

/* Exception: TYPEERROR: A.X(...) is undefined @Scratchpad/1:14:1 */

We can GET the desired output by “return this” in each function.
Now “this” is the object “A”. So, A.x() will result in CONSOLE logging ‘x’ followed by returning the object “A” to y().
After that the function A.y() will print ‘y’ followed by returning the object “A” to z().
Finally, ‘z’ is printed on console.

var A = {     x: function() {         console.log('x');         return this;     },     y: function() {         console.log('y');         return this;     },     z: function() {         console.log('z');         return this;     }  } A.x().y().z();  //Output x y z


Discussion

No Comment Found