this
(aka "the context") is a special keyword inside each function and its value only depends on how
the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
To learn more about this
, have a look at the MDN documentation.
What is the difference between "let" and "var"?
How do I replace all occurrences of a string?
How to randomize (shuffle) a JavaScript array?
How do I format a date in JavaScript?
How can I get query string values in JavaScript?
How do I check if a directory exists? "is_dir", "file_exists" or both?
How to create an array from a CSV file using PHP
How to pass an array within a query string?