[英]Is this possible to design a function which takes a parameter and returns an object which holds multiple properties or functions
例如:
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 作为构造函数,因此您可以更改代码以使用传统的 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());
或者,您可以从箭头 function 返回 object
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
但从未执行过 function。 这有效:
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
基本上和我上面的第二个例子一样
除了其他答案之外,如果您想使用箭头 function 您可以通过将 object 包装在括号中来使用它:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.