2014-01-19 42 views
0

我有一個對象wihtin一個功能性,我不知道如何訪問對象的屬性,改變他們,給它添加或興田對象刪除:我需要幫助的訪問對象的性質在

function Example(test) { 
    test={}; 
    test.firstTry='One'; 
    test.secondTry='Two'; 
    console.log(test); 
} 
x=new Example("I don't know where to go from here, I want to access test.firstTry and test.secondTry"); 
+0

你不能訪問這些功能之外,它們是未知的外部世界 –

+0

謝謝大家,我沒有忘記「這個」,我在實例的實例也忘了「[...]」。它應該是x = new示例(['...']); – davidLeak

回答

1

爲了test屬性在構造函數中的Example對象使用this

function Example(test){ 
    this.test={}; 
    this.test.firstTry='One'; 
    this.test.secondTry='Two'; 
} 

var x = new Example({}); 
console.log(x.test.firstTry); 
1

這些屬性是僅在函數內的局部變量中可用的對象的成員。除非您修改該功能,否則無法在功能外訪問它們。

您可以將該變量作爲對象屬性公開。

this.test = test; 

然後

x.test.firstTry; 
1

如果您使用的是new關鍵字,你應該使用this

function Example() { 
    this.firstTry = 'One'; 
    this.secondTry = 'Two'; 
} 

var x = new Example(); 
console.log(x); 

輸出:Example {firstTry: "One", secondTry: "Two"}

你也可以返回一個對象相反:

function Example() { 
    var test = {}; 
    test.firstTry = 'One'; 
    test.secondTry = 'Two'; 
    return test; 
} 

var x = Example(); 
console.log(x); 

輸出:Object {firstTry: "One", secondTry: "Two"}

0

看到這個http://jsfiddle.net/kukiwon/fFzWh/。你忘了添加一個return語句。

function Example(test){ 
    test={}; 
    test.firstTry='One'; 
    test.secondTry='Two'; 
    return test; 
} 

var x=new Example("I don't know where to go from here, I want to access test.firstTry and test.secondTry"); 
alert(x.firstTry); 
alert(x.secondTry);