What is “this” in Javascript

What is “this” in Javascript — especially, when you use bind( ), arrow function and regular function?

function checkThis() {
return this;
}
// In a browser:
checkThis() === window; // true
// In Node:
checkThis() === global; // true
let user = {
name: "Maya",
age: 30,
callMe() {
alert(this.name);
alert(user.name);
}
};user.callMe(); // will output "Maya", and then "Maya" again
let human = { name: "Maya" };
let dog = { name: "Pillow" };
function sayHi() {
alert( this.name );
}
// assign the function into two objects
human.sayHi = sayHi;
dog.sayHi = sayHi;
human.sayHi(); // Maya  (this == human)
dog['sayHi'](); // Pillow  (this == dog)
function addThis() {
console.log(this) // 'this' = "hello" because it is bound to "hello"
}
function noThis() {
console.log(this); // 'this' = window object
}
let runMe = addThis.bind("hello"); // ties "hello" to addThisrunMe(); // executes addThis and returns "hello" noThis(); // executes noThis and returns a window object

The answers are : YES AND NO.

Yes, if the inner function is an arrow function.

function parentFunc() {  console.log(this) // 'this' = "hello"

childFuncArrow = () => {
console.log(this); // 'this' = "hello"
};
childFuncArrow();

function childFuncNormal() {
console.log(this); // 'this' = the window object - oh no!
}
childFuncNormal();

}
let runMe = parentFunc.bind("hello"); runMe(); // execute parentFunc which outputs "hello", "hello", Window object
let human = {  name: "Maya",

twoFunctions() {
console.log(this.name); // output "Maya" let arrow = () => console.log(this.name); // output "Maya" arrow();

function notArrow() {
console.log(this.name); // output "undefined" - because it tries to call window.name
}

notArrow();
},
}

human.twoFunctions(); // Will output "Maya", "Maya" and "undefined"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maya Novarini

Frontend developer with master’s degrees in Computer Science and Politics. Passionate about animals, software accessibility and UI/UX design.