例如:
var resultList = [];
var objectName = (userName) => {
};
objectName.rowCount;// 回傳總計數
objectName.fetchNext();// 更新的資料將在 resultList 中可用
我嘗試了多種解決方案,但沒有像
var resultList = [];
var objectName = (userName) => {
var rowCount = 0;
init() {
// make call to server and read data
rowCount = 5; // setting dummy data
};
fetchNext = function(){
// logic here
resultList = [] // new data
};
init();
};
編輯
又一次嘗試
var x = function(){
var a = function(){console.log('a');};
var b = function(){console.log('b');};
return {a: a, b: b};
}
x.a(); // not able to call this function
uj5u.com熱心網友回復:
您不能將箭頭函式用作建構式,因此您可以更改代碼以使用傳統函式:
function objectName(userName) {
var rowCount = 0;
init = function() {
// make call to server and read data
rowCount = 5; // setting dummy data
};
this.fetchNext = function(){
// logic here
const resultList = [] // new data
return resultList;
};
init();
};
var myObj = new objectName("foo");
console.log(myObj.fetchNext());
或者,您可以從箭頭函式回傳一個物件
var objectName = (userName) => {
var rowCount = 0;
function init() {
// make call to server and read data
rowCount = 5; // setting dummy data
};
init();
return {
fetchNext: function(){
// logic here
const resultList = [] // new data
return resultList;
}
}
};
var myObj = objectName("Foo");
console.log(myObj.fetchNext());
有關的:
- “箭頭函式”和“函式”是否等效/可互換?
為了完整起見,您的編輯不起作用的原因是您定義x但從未執行過該功能。這有效:
var x = function(){
var a = function(){console.log('a');};
var b = function(){console.log('b');};
return {a: a, b: b};
}
x().a(); // must execute x to get the result
基本上和我上面的第二個例子一樣
uj5u.com熱心網友回復:
除了其他答案,如果你想使用箭頭函式,你可以通過將物件包裝在括號中來使用它:
const objectName = (userName) => ({
rowCount: 0,
resultList: [],
init() {
this.rowCount = 5;
},
fetchNext() {
// fetch results
this.resultList = [1, 2, 3, 4];
}
});
const results = objectName('kyroath');
console.log('before init():', results.rowCount); // 0
results.init()
console.log('after init():', results.rowCount); // 5
console.log('before fetchNext():', results.resultList); // []
results.fetchNext()
console.log('after fetchNext():', results.resultList); // [1, 2, 3, 4]
uj5u.com熱心網友回復:
您只是在尋找課程嗎?
class Obj {
constructor() {
this.rowCount = 0;
this.resultList = [];
}
init() {
// make call to server and read data
this.rowCount = 5; // setting dummy data
}
fetchNext() {
// logic here
this.resultList.push(1); // new data
return this.resultList;
}
}
const obj = new Obj("userName");
obj.init();
const row = obj.rowCount;
const res = obj.fetchNext();
console.log(row);
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410837.html
標籤:
