Skip to content

Instantly share code, notes, and snippets.

@airbr
Created August 30, 2020 03:17
Show Gist options
  • Save airbr/b4d80cd117a40167d103dbaa82006daa to your computer and use it in GitHub Desktop.
Save airbr/b4d80cd117a40167d103dbaa82006daa to your computer and use it in GitHub Desktop.
///////////////////////////////////
// 5. More about Objects; Constructors and Prototypes
// Objects can contain functions.
var myObj = {
myFunc: function(){
return "Hello world!";
}
};
myObj.myFunc(); // = "Hello world!"
// When functions attached to an object are called, they can access the object
// they're attached to using the `this` keyword.
myObj = {
myString: "Hello world!",
myFunc: function(){
return this.myString;
}
};
myObj.myFunc(); // = "Hello world!"
// What this is set to has to do with how the function is called, not where
// it's defined. So, our function doesn't work if it isn't called in the
// context of the object.
var myFunc = myObj.myFunc;
myFunc(); // = undefined
// Inversely, a function can be assigned to the object and gain access to it
// through `this`, even if it wasn't attached when it was defined.
var myOtherFunc = function(){
return this.myString.toUpperCase();
};
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"
// We can also specify a context for a function to execute in when we invoke it
// using `call` or `apply`.
var anotherFunc = function(s){
return this.myString + s;
};
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
// The `apply` function is nearly identical, but takes an array for an argument
// list.
anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
// This is useful when working with a function that accepts a sequence of
// arguments and you want to pass an array.
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment