Global Object, Methods, This
A Closer Look
Let's check out:
- global object
- methods
- and this
The Global Object
What's the name of the global object in node (pssst… the answer is right there)? →
I gave that one away; it's… global
Let's check out what's in the global object right now!
console.log(global)
And let's try (inadvertently, of course. oops!) adding something to the global object:
function makeMessage() {
// oops, forgot var/let/const... I'm a global!
message = 'hello there';
}
makeMessage();
console.log(message);
console.log(global.message);
(oh yeah, in the browser, the global object is window
)
A Variable That's Not There Yet
And… what do I get if I try to print out a property on the global object that doesn't exist? →
console.log(global.surprise);
undefined
// just like accessing a property that doesn't exist
// on any ol' object:
obj = {};
console.log(obj.unicorn);
Methods
What's a method? →
- a method is an object property that is a function (or a function within the context of an object).
- you can create methods pretty easily…
const person = {};
person.emote = function() {
console.log('(っ˘̩╭╮˘̩)っ');
};
person.emote(); // sad face - (っ˘̩╭╮˘̩)っ
To call a method on an object, use:
- the object's name
- followed by a dot,
- then a method name
- …and finally parentheses (with an optional list of arguments!)
Functions
When a function is invoked, it has access to its declared parameters. It also has access to two additional parameters. What are they? →
this
arguments
What's the arguments
object? →
arguments is an array like object that contains all of the arguments (surprise!) passed in to a function. What is the preferred way of declaring an arbiratry number of parameters for a function in ES6, though →
use the rest operator: ...args
With arguments/...args
out of the way, let's talk about this
(but before we do, a detour)→
Executing a Function
There are actually a few different ways (patterns) that a function can be called. What are some ways of executing a function that we've seen so far? →
- as a regular function:
myFunction()
- as a method if the function is attached to an object:
obj.myFunction()
- via a method on a function object (!) (you remember those, right? →)
call
apply
bind
Depending on which invovaction pattern we use, a function's this
is bound to a different value. →
A function's this
varies based on how the function is invoked!
Calling a Method, This
When a function is invoked as a method, this
is bound to the object that it's called on. Here's an example. →
function showEmotion() {
console.log(this.emotion);
}
const person1 = {emotion:"(• ε •)", emote: showEmotion};
const person2 = {emotion:"(╯°□°)╯︵ ┻━┻", emote: showEmotion};
person1.emote(); // (• ε •)
person2.emote(); // (╯°□°)╯︵ ┻━┻