Prévia do material em texto
JAVASCRIPT Normal Vs Arrow Function JS SWIPEIn Javascript we have two ways to define a function. One is using the function keyword: JS App.js function test (msg) { return `Hey ${msg} ; } And the other is using a arrow: JS App.js const arrowFunction = (msg) => { return ${msg}argument keyword: You cannot use argument keyword inside arrow functions JS App.js function regularFunction (a, b) { console.log(arguments) } regularFunction (1,2) // Arguments [1, 2] const arrowFunction = (a,b) { console.log(arguments) } arrowFunction (1,2) //ReferenceError : argumnets is not definednew keyword: Regular functions are constructible, they can be called using the new keyword but not arrow functions JS App.js function add (x, , y) { console. log (x + y) } let sum = new add (2,3) ; // 5 JS App.js let add = (x, y) console. log (x + y) ; const sum = new add (2,4); // TypeError: add is not a constructorthis keyword: Inside regular function this is equal to the execution context, this could be global object, an object that owns the method or itself if using the new keyword JS App.js var name = "Dishant" let newObject = { name : "Siddharth" , arrowFunc: { console. log }, regularFunc() { console. log (this. name) ; } new0bject.arrowFunc() ; // Dishant new0bject.regularFunc() ; // SiddharthMethods: You can define methods in class using regular function. JS App.js class FullName { constructor (name) { this.name = name; } result { console. log (this.name) } } let name = new FullName ( "Burhan")But if you apply this method as a callback you need to bind it first JS App.js // Without bind setTimeout (name. result, 2000) // after 1 second logs // With bind setTimeout (name.result.bind (name), 2000) // BurhanBut if you use arrow function then you don't need to bind JS App.js class FullName { constructor (name) { this.name = name; } result = => { console. log (this.name) } } let name = new FullName ("Roy") setTimeout (name. result, , 2000) // RoyDid you learn something new?