2014-04-10 70 views
-5

嗨,朋友們真的堅持在JavaScript中的this財產。這困惑在javascript

Collection.prototype.onOpen = function() { 

    var self = this; 

    this.buffer = function() { 
return this 
} 

    self.doQueue(); 
}; 

我只需要知道什麼this對應here..Is this相當於收藏在這裏。

請幫我..Any幫助將不勝感激..Thanks

+1

只是看你貼的代碼的理解,這是不可能說什麼'this'會。它完全取決於如何調用「onOpen」函數。 – Pointy

+0

你應該閱讀範圍但在你的情況爲什麼不console.log它,如果你不確定?它會在jiffy中告訴你.. –

+0

我建議閱讀關於'this'的MDN文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this。 –

回答

2

的取決於功能是如何調用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` 
+0

所以你說這是指收集這裏..?對嗎? – user3517846

+0

@ user3517846:No. –

+3

@ user3517846你沒有告訴我們你是如何調用它 –