是否可以设计一个函数,该函数接受一个参数并返回一个包含多个属性或函数的对象



例如:

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

您不能将箭头函数用作构造函数,因此您可以将代码更改为使用传统函数:

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

与上面的第二个例子基本相同

除了其他答案之外,如果你想使用箭头函数,你可以这样使用它,方法是将对象包装在paransition中:

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]

你只是在找一个class吗?

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);

最新更新