this - when used within the object, it refers to the object itself.
=================
let yourObject = {
name: "Bell Cranel",
age: 20,
introduceYourself(){
document.writeln('I am ${this.name}. I'm ${this.age} years old.');
}
myJob: function(){
document.write("I am a dungeon adventurer!");
}
}
function whoAreYou(){
yourObject.introduceYourself();
yourObject.myJob();
}
=================
HTML
whoAreYou()
Result:
I am Bell Cranel. I'm 20 years old. I am a dungeon adventurer!
Note: You can also use the this keyword outside of the object declaration.
==================
let objectX = {
name: "Bell Cranel",
age: "20"
}
let objectY = {
name: "Linda L",
age: 18
}
function introduceYourself(){
document.write('name: ${this.name} and age: ${this.age}.');
}
function whoAreYou(){
objectX.yourFunction = introduceYourself;
objectY.yourFunction = introduceYourself;
objectX.yourFunction();
objectY.yourFunction();
}
==================
HTML
whoAreYou()
Result:
name: Bell Cranel and age: 20. name: Linda L and age: 18.
Using the this keyword in an arrow function
==================
let objectX = {
name: "Bell Cranel",
askName(){
let arrow = () => prompt("Enter your name: ", this.name);
this.name = arrow();
}
}
let introduceYourself = () => documen.writeln('My name is ${this.name}...');
function introduceYourselfRev1(){
document.writeln('My name is ${this.name}...');
}
function whoAreYou(
objectX.askName();
objectX.whoYouArrow = introduceYourself;
objectX.whoYouArrow();
objectX.whoYouFunction = introduceYourselfRev1;
objectX.whoYouFunction();
)
==================
HTML
whoAreYou()
Result: (It will ask for your name)
My name is ... My name is Bell Cranel...
Note:
1. If you used the this keyword in an arrow function that is within the object body, it returns the desired result.
2. If you used the this keyword in an arrow function that is outside the object body, it will return an undefined. That is why the first result is empty.
3. The second result using the this keyword in a function that is outside the object body, it returns the desired result.
YOU ARE READING
Javascript Programming
RandomI am just documenting things what i learned online in here. I do express things in my own words. And I create my own program samples which serves as my practice. I do this so that when someday I would need some notes to review, I can just visit in h...
