The value of this
changes depending upon how the function was invoked;
Collection.prototype.onOpen(); // `this` refers to `Collection.prototype`
// vs
var c = new Collection();
c.onOpen(); // `this` refers to `c`
// vs
var o = {};
Collection.prototype.onOpen.call(o); // `this` refers to `o`
// vs
var foo = Collection.prototype.onOpen;
foo(); // `this` could be `window` or undefined
Perhaps a some examples will aid you in your understanding of how this
changes
// set up
var o = {}; // So we have an empty Object called `o`
function foo() { // and a function called `foo` which lets
return this; // us see the value of `this` by returning
} // it
o.bar = foo; // and set `bar` of `o` to be `foo`, too
// example 1
foo(); // `window` if in global scope (see example 4 for other scopes)
// example 2
o.bar(); // `o`
// example 3
foo.call(o); // `o`, same as `o.bar.call(o);`
foo.apply(o); // `o`, same as `o.bar.apply(o);`
// example 4, complex
(function () { // IIFE creates a new scope
"use strict"; // and let's have it in in strict mode
function baz() {
return this;
}
return baz();
}()); // = `this` from `baz` = undefined
// example 5, inheritance
function Fizz() {
}
Fizz.prototype.buzz = foo;
var fizz = new Fizz();
fizz.buzz(); // `fizz`
14
solved This confuses in javascript [duplicate]