Created
August 30, 2020 03:17
-
-
Save airbr/b4d80cd117a40167d103dbaa82006daa to your computer and use it in GitHub Desktop.
snippet from https://learnxinyminutes.com/docs/javascript/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////// | |
// 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