Santha Kumar Chigurupati’s Post

Call, Apply, or Bind? 🚀 Mastering the "this" context in JavaScript Ever wondered how to borrow methods or control the this keyword in JavaScript? These three methods are essential for every JS developer's toolkit. Here’s a quick breakdown: 📞 .call(): Invokes the function immediately. Arguments are passed individually. fullName.call(personObject, "Hyderabad", "Telangana"); 📧 .apply(): Invokes the function immediately. Arguments are passed as an Array. fullNameWithAddress.apply(personObject2, ["Bangalore", "Karnataka", "India"]); 🔗 .bind(): Does not invoke the function immediately. It returns a new function with the context locked in, which you can call later. let bindMethod = fullNameWithAddresBind.bind(personObject3, "Chennai", "Tamilnadu"); bindMethod(); The Key Difference? It’s all about how you handle arguments and execution timing. Use call for speed, apply when working with arrays (like math operations), and bind for event listeners or delayed execution. Check out my code snippets below to see them in action! 👇 let personObject = { firstName: "Santha Kumar", lastName: "Chigurupati", } let fullName = function (city, state) { console.log(this.firstName + " " + this.lastName + " " + city + " , " + state); } // CALL fullName.call(personObject, "Hyderabad", "Telangana"); let personObject2 = { firstName: "Saahus Neal", lastName: "Chigurupati", } let fullNameWithAddress = function(city, state, country) { console.log(this.firstName + " " + this.lastName + " " + city + " " + state + " " + country) } // APPLY fullNameWithAddress.apply(personObject2, ["Banglore", "Karnataka", "India"]) let personObject3 = { firstName: "Suhaas Neal", lastName: "Chigurupati", } let fullNameWithAddresBind = function(city, state, country, profession) { console.log(this.firstName + " " + this.lastName + " " + city + " " + state + " " + country + " " + profession) } //BIND let bindMethod = fullNameWithAddresBind.bind(personObject3, "Chennai", "Tamilnadu", "India", "Artist"); bindMethod() #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #JSFundamentals

To view or add a comment, sign in

Explore content categories