2015-01-15 73 views
-1

當談到javascript對象變量時,我感到非常困惑。 如果我正在創建一個對象構造函數,使用這個有什麼區別。並使用var? EG:Javascript對象和變量

var myObj = function(x){ 
    this.thing = x; 
    var otherThing = 20; 
    var lastThing = "I wish I knew more about javascript objects"; 
} 

另一件事是當設置這一點。變量在對象內使用,在上面的情況下使用:

this['thing']; 

是嗎?

在此先感謝。

回答

1

這裏是一個參考對象上面向MDN的javascript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

如果您使用var關鍵字,然後這些變量將是私人你的對象。你將不能夠做到myObj.otherThing

如果您使用此,則變量是你對象的屬性,所以你可以使用myObj.thing

當你從對象中調用一個變量你會使用this.thing,在你要使用myObj.thing的對象之外

希望有幫助。

+0

輝煌。這只是我正在尋找的澄清。感謝您回答我的noob問題:) –

0

沒錯。注意:

var fn = function(x){ 
    this[ 'thing' ] = x; 
    return this; 
} 

console.log(fn(2)); // return window, and function set window[ 'thing' ] = 2 
console.log(fn.apply(document, [ 3 ])); // return document, and function set window.document[ 'thing' ] = 3 

「this」指的是執行函數的上下文。如果你在fn(2)之類的窗口中運行函數,則上下文就是窗口。使用apply更改上下文。然後,如果您希望thing處於當前功能中,請在功能上下文中使用var thing;

window[ 'thing' ] // is the same as window.thing 
window[ '2' ] // is the same as window[ 2 ], but not window.2 (syntax error)