Question About .this in JavaScript

What is the importance of this.

Link: The this Keyword

During this lesson it teaches you how to reference a calling object using this. Could we not just use the objects name then dot notation for the property instead of ‘this.’ . Since they both do the same thing, according to the console results. My examples below.

Original Code Using ‘this.’: this.dietType

const goat = {
dietType: ‘herbivore’,
makeSound() {
console.log(‘baaa’);
},
diet() {
console.log(this.dietType);
}
};

goat.diet(); // Prints ‘herbivore’

Using ObjectName.Property: goat.dietType

const goat = {
dietType: ‘herbivore’,
makeSound() {
console.log(‘baaa’);
},
diet() {
console.log(goat.dietType);
}
};

goat.diet(); // Prints ‘herbivore’

  • What is the benefit of using this. vs objectName.Property ?
  • What will happen if you dont use this. and use the objectName instead?
  • Does it affect the way HTML will show the results your looking for?
  • Can someone show me why you would not want to use the objectsName instead of this.

I think this shows its usefulness when dealing with many instances of the same (or similar) object, not just a single object.

If you wanted to make more than one goat, which goat would you be referring to when calling goat.diet()? You would have to change that line of code for each goat object.

const goatA = {
	dietType: 'herbivore',
	makeSound() {
		console.log('Baaaa!')
	},
	diet() {
		console.log(goatA.dietType) // <-- using objectName
	}
}

const goatB = {
	dietType: 'herbivore',
	makeSound() {
		console.log('Baaaa!')
	},
	diet() {
		console.log(goatB.dietType) // <-- using objectName
	}
}

But if you needed a herd of goats it will be a lot of repeated code just to change one line, and there’s also a greater potential for bugs. We can avoid these issues if we make a factory function and use this. It will be less repeated code and we can be sure the property being called belongs to the object.

(This might be slightly ahead of where you are in the object lessons).

// This function will return a goat object
const goatFactory = () => {
	return {
		dietType: 'herbivore',
		makeSound() {
			console.log('Baaaa!')
		},
		diet() {
			console.log(this.dietType); //<-- using this
		}
	}
}

let goatA = goatFactory();
let goatB = goatFactory();

We get the same result with less code.

So in short - the benefit is less code that is not prone to errors, which may happen if you use objectName instead of this. These errors could somehow mess with the results of your HTML, for example, displaying the property of goatA when you meant to display a property of goatB.

2 Likes

Using ‘this’ keyword instead of the object’s name is really helpful because take a look at the example below:

var user = {

    name : 'John',

    show_name : function(){

        console.log(this.name);

        // OR

        console.log(user.name);
    }
};

user2 = Object.create( user );
user2.name = "user 2";

user2.show_name();

the .name() method will still print ‘John’ but if you use this.name then the updated property value will be printed!

I hope this helps you understand this keyword better.

1 Like

@goku-kun Thanks for the reply!

So you created a second object correct? Then mutated the first object to change the value of property name to show “user 2”. Which when ran in console it prints “user 2”.

  • Are the results still the same whether you use this. or the objectName or would “john” print in the new object that was mutated instead of “user 2”?

My thoughts here are inside the local scope it should not matter if this. or objectName is listed because nothing has been changed inside the local scope. Only change I see is a new objectName created (user to user2).

  • So how did this. work any different than using the objectName?
  • I would like to understand the benefits of using this.

@ryansup thanks for reply!

So I still don’t see the benefit of this. vs objectName. When I placed your code with Object name it still does the same thing as if I where to use this.

Your Code: Using objectName

const goatFactory = () => {
	return {
		dietType: 'herbivore',
		makeSound() {
			console.log('Baaaa!')
		},
		diet() {
			console.log(goatFactory.dietType); //<-- using objectName instead of this.
		}
	}
}

let goatA = goatFactory();
let goatB = goatFactory();

goatA.dietType = 'Carno'// added a change to diet

console.log(goatA)// Prints Carno
console.log(goatB)// Prints herbivore
  • Am I missing something unique here?

Try running this now:

goatA.diet();
goatB.diet();

with your use of the object name instead of this in the diet() method you get

undefined
undefined

Using this you get

Carno 
herbivore 
1 Like

@selectall Thank you for your response!

This is what I was trying to understand!

You cannot get a returned value using the objectName but you can get a return value using the this. keyword.

Bonus Question

  • Why is that so…?

You can get a return value but not in this example because goatFactory is a function that returns an object, it does not know the properties of the object it is returning.

		diet() {
               console.log(typeof goatFactory); // Prints "Function"
		}

You see Carno and herbivore in your example because you are logging the entire object:

The undefined issue is still present in your code but it was harder to catch.

:sunglasses: :point_right:

When you have an object nested in another object you would use objectName the way your were initially describing, so it does have its uses.

let parent = {
	name: "parent",
	child: {
		name: "Pete"
	}
}

console.log(parent.name); // "parent"
console.log(parent.child.name); // "Pete"


// accessing the child object with a function using this:
parent = {
	name: "parent",
	callChild() {
		console.log(`${this.child.name}!`); // <-- using this
	},
	child: {
		name: "Pete"
	}
}

parent.callChild(); // Logs "Pete!"

// You can replace this with the objectName and it still works
parent = {
	name: "parent",
	callChild() {
		console.log(`${parent.child.name}!`); // <-- using objectName
	},
	child: {
		name: "Pete"
	}
}

parent.callChild(); // Logs "Pete!"

JavaScript is loosely typed - seems like we do a lot of things that don’t seem necessary to add order to the chaos.

1 Like