2017-02-02 31 views
0

我想通過函數創建我的對象,但我無法弄清楚getter函數的語法。函數內的Javascript getter函數

var myObject = 
{ 
    0:123, 

    get a() 
    { 
     return this[0]; 
    } 
} 


console.log("This works: " + myObject.a); 


function test() 
{ 
    this[0] = 123; 

// error 
    this.a = get function() 
    { 
    return this[0]; 
    }; 
} 


var myTest = new test(); 

console.log(myTest.a); 

在測試功能,get函數的分配拋出一個缺少分號錯誤,如果我刪除關鍵字「功能」,它說,得到的是沒有定義。

如何爲我的函數中的當前對象分配getter函數?

+0

我不認爲'變種F =獲取函數(){...} '語法是正確的,用'var f = get {...}'代替。您的函數'test'無法解析,而刪除'function()'使其起作用 – Aaron

+1

由於這不是用於[定義getter]的正確語法(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters) –

回答

2

你可以嘗試這樣的事:

var myObject = 
{ 
    0:123, 

    get a() 
    { 
     return this[0]; 
    } 
} 


console.log("This works: " + myObject.a); 


function test() 
{ 
    this[0] = 123; 

    Object.defineProperties(this, {"a": { get: function() { 
     return this[0]; 
    }}}); 
} 


var myTest = new test(); 

console.log(myTest.a); 
+0

是否有一種類似於我正在嘗試執行的簡化版本,或者這是唯一方法? – John

+0

我不這麼認爲。您只能使用對象文字的簡短方式。 \t這是儘可能接近,在這種情況下,你不會傳回'這'。 功能測試(){ \t \t 返回\t \t {\t \t \t 「0」:123, \t \t得到(){ \t \t \t返回這個[ 「0」]; \t \t} \t \t \t \t \t} \t} –

0

也許這會爲你工作:

 function test() 
     { 
      this[0] = 123; 

      Object.defineProperty(this, "a", { get: function() { return this[0]; } }); 
     }