Sitemap
codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — all about “this” keyword

4 min readFeb 1, 2018

--

Zoom image will be displayed
learn with chime tunes — Photo by NC Patro on Unsplash

What is “this” keyword in JavaScript

function bike() {
console.log(this.name);
}

var name = "Ninja";
var obj1 = { name: "Pulsar", bike: bike };
var obj2 = { name: "Gixxer", bike: bike };

bike(); // "Ninja"
obj1.bike(); // "Pulsar"
obj2.bike(); // "Gixxer"

Default and Implicit binding of “this”

var obj1 = {
name: "Pulsar",
bike: function() {
console.log(this.name);
}
}
var obj2 = { name: "Gixxer", bike: obj1.bike };
var name = "Ninja";
var bike = obj1.bike;

bike(); // "Ninja"
obj1.bike(); // "Pulsar"
obj2.bike(); // "Gixxer"

Explicit and Fixed Binding of “this” keyword

function bike() {
console.log(this.name);
}

var name = "Ninja";
var obj = { name: "Pulsar" }

bike(); // "Ninja"
bike.call(obj); // "Pulsar"
var bike = function() {
console.log(this.name);
}
var name = "Ninja";
var obj1 = { name: "Pulsar" };
var obj2 = { name: "Gixxer" };

var originalBikeFun = bike;
bike = function() {
originalBikeFun.call(obj1);
};

bike(); // "Pulsar"
bike.call(obj2); // "Pulsar"

The “new” keyword in JavaScript

function bike() {
var name = "Ninja";
this.maker = "Kawasaki";
console.log(this.name + " " + maker); // undefined Bajaj
}

var name = "Pulsar";
var maker = "Bajaj";

obj = new bike();
console.log(obj.maker); // "Kawasaki"

Precedence of “this” keyword bindings

If you like this post and it was helpful, please click the clap 👏 button multiple times to show the support, thank you.

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

NC Patro
NC Patro

Written by NC Patro

Developer | Mentor | Public Speaker | Technical Blogger | Love for Photography and Programming | twitter: @ncpatro

Responses (12)