的取決於功能是如何調用this
變化值;
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
也許一些例子將幫助你在你如何this
改變
// 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`
只是看你貼的代碼的理解,這是不可能說什麼'this'會。它完全取決於如何調用「onOpen」函數。 – Pointy
你應該閱讀範圍但在你的情況爲什麼不console.log它,如果你不確定?它會在jiffy中告訴你.. –
我建議閱讀關於'this'的MDN文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this。 –