我正在使用直接的 Javascript(請不要使用 JQuery 或類似的東西)。我已經實作了一個包裝陣列的類,因此:
class Ctrls
{
_items = new Array();
constructor()
{
this._items = new Array();
}
Add(oCtrl)
{
this._items.push( { key:oCtrl.Name, value:oCtrl } );
}
Clear()
{
this._items = new Array();
}
get Count()
{
return this._items.length;
}
get Item(index)
{
// get the index'th item.
// If item is numeric, this is an index.
// If item is a string, this is a control name
if (Number.isInteger(index))
{
return this._items(index).value;
}
else
{
item = this._items.find(element => (element.value.Name == index));
return item;
}
}
get Items()
{
return this._items; // in case we desperately need to
}
}
我在頁面加載時收到錯誤,位于get Item(index),即Uncaught SyntaxError: Getter must not have any formal parameters。我來自 C# 世界,正在尋找相當于:
public Ctrl Item(iIndex)
{
get
{
return _items[iIndex];
}
}
如何在 Javascript 中索引 getter?
編輯(1):我已經建議get Item變成一個函式,但是如果我將定義更改為:
function GetItem(index) // returns Ctrl
{
// get the index'th item.
// If item is numeric, this is an index.
// If item is a string, this is a control name
if (Number.isInteger(index))
{
return this._items(index).value;
}
else
{
item = this._items.find(element => (element.value.Name == index));
return item;
}
}
我在頁面加載時收到此錯誤:Uncaught SyntaxError: Unexpected identifier在線function GetItem...
編輯(2):將以上內容修改為:
GetItem(index) // returns Ctrl
{
// get the index'th item.
// If item is numeric, this is an index.
// If item is a string, this is a control name
if (Number.isInteger(index))
{
return this._items(index).value;
}
else
{
item = this._items.find(element => (element.value.Name == index));
return item;
}
}
奇怪的是,因為類中的函式不使用function關鍵字。這現在有效。謝謝大家。
uj5u.com熱心網友回復:
“您不能將引數傳遞給 JS 中的 getter”。理論上:是的,你不能那樣做。但實際上:函式是 JS 中的一等公民,因此它們可以是函式的引數或回傳值。你可以這樣做:
class GetterWithParameter {
constructor() {
this.array = ["index 0", "index 1", "index 2"]
}
get itemAtIndex() {
return (idx) => this.array[idx]
}
}
const getterWithParameter = new GetterWithParameter()
const idx0 = getterWithParameter.itemAtIndex(0)
const idx1 = getterWithParameter.itemAtIndex(1)
const idx2 = getterWithParameter.itemAtIndex(2)
console.log("item at index 0:", idx0)
console.log("item at index 1:", idx1)
console.log("item at index 2:", idx2)
因此,雖然getter不能有引數,但您可以回傳一個可以接收引數的函式 - 并使用它。
當然,用法似乎與在需要相同引數的類上定義函式相同 - 但您仍然使用getter.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440087.html
標籤:javascript 班级 索引 获取属性
