- If a function is called with the new keyword,
this
will be the resulting object. - If a function is called with
.call()
,.apply()
or.bind()
,this
will be the object that is passed in. - If a function is called on an object,
obj.foo()
,this
will be the object it was called on. - If a function is called on its own,
sayMyName()
,this
will be eitherundefined
(if inuse strict;
mode) or the global object (if in non-strict mode).
If a function is called with the new keyword, this
will be the resulting object.
let myName = new String('Ahmad Awais');
typeOf(myName); // object <================== this is the resulting object.
If a function is called with .call()
, .apply()
or .bind()
, this
will be the object that is passed in.
let person = {
name: "Ahmad Awais"
};
let sayMyName = function() {
console.log(this.name);
};
sayMyName.call(person); // Ahmad Awais β <================== this is the object that is passed in i.e. person.
If a function is called on an object, obj.foo()
, this
will be the object it was called on.
let person = {
name: "Ahmad Awais",
sayMyName: function() {
console.log(this.name);
}
};
person.sayMyName(); // Ahmad Awais <================== this is the object on which the functions was called i.e. person.
If a function is called on its own, sayMyName()
, this
will be either undefined
(if in use strict;
mode) or the global object (if in non-strict mode).
"use strict";
let name = "Ahmad Awais";
let sayMyName = function() {
console.log(this.name);
};
sayMyName(); // undefined <================== this is undefined.
An arrow function expression has a shorter syntax than a function expression and does not have its own this
.
MIT Β© Ahmad Awais.
Kyle Simpson for his incredible work on You Don't Know JS and the good folks at Icons8.
The Concept of `this` in JavaScript π° Learn the concept of `this` in JavaScript! β [five simple concepts]. |
|
A FOSS (Free & Open Source Software) project developed by Ahmad Awais. | |
Follow Ahmad's #FOSS work on GitHub @AhmadAwais β Say Hi on Twitter @MrAhmadAwais | π |
Hello, we're the WordPress Couple!
I (Ahmad Awais) am a Full Stack Web Developer and a regular core contributor at WordPress. My significant other (Maedah Batool) is a Technical Project Manager, and she's also a WordPress Core Contributor. Together with our team, we run the WPCouple.com.
If you'd like to get insights into our love for open source software, professional full stack development, WordPress community, the growth of JavaScript or growing a family, building, and bootstrapping a business, then subscribe to our premium newsletter called β£ The WordPress Takeaway!
Project Backers & TheDevCouple Partners β‘οΈ
This FOSS (free and open source software) project is updated and maintained with the help of awesome businesses listed below.
β What/How? Read more about it β
For anything else, tweet at @MrAhmadAwais
I have released a video course to help you become a better developer β Become a VSCode Power User β
VSCode