Learn MORE JavaScript on the ServiceNow Platform: Lesson 2 Exercise - Understanding "this"
Okay, exercise time. So to help you really get it in your brain, how this works,
we're going to do this exercise. I want you to create a script
in which you define an object named userProfile with properties
name and logName. Include a method logName that logs
the user's name using “this.” Then outside the object, invoke this method in a different context
to see how this goes. I’ve provided a couple of hints for you
in case you need it, but otherwise,
go ahead and press pause right now and I'll see you on the flip side
to see how your solution compares to mine. See you Okay, we're back. Let's go ahead and check it out. So I have already put on the screen
userProfile object
that I created according to the prompt. You'll see that
I have a userProfile object. It has a name property. I use John Doe in there
and then I created a function within that object, logName,
and in it just calls this.name. And so if I go ahead and say
userProfile and logName() to call it outside of the context of that
object, we'll see what it does. Let's go ahead and copy
that into ServiceNow and see what happens. There it is, John Doe. And so to illustrate what happens, though,
if you try to do something separate with that method
within that object and create it in a different context, you might get some unexpected results. So I'm going to try to break that context
just for demonstration here. I'm going to make a new test function I'm going to declare it as the logName method from userProfile,
and then I'm going to try to call that new function. And you can see it comes out as undefined because it has no idea what
this is anymore. as a bonus, I'm going to show you
a cool way to call or apply a change to the context of “this”
when calling logName. And so if I have a different profile,
I'm going to go ahead and call it anotherProfile. Now, very creative on naming sometimes, and I'm going to give it a different name. So we'll say Jane Smith instead and close that new object. I'm going to go ahead
and say userProfile.logName and then call another profile. So what's happening here is I'm changing the context of that of that method within userProfile and saying giving it a different context
to apply that method to. So if I run the script,
you'll see it called Jane Smith. Kind of cool.
https://www.youtube.com/watch?v=bGPqfBUj77Q