JS。对象函数返回函数返回
问题描述:
我有两个内部函数的对象。第一个工作完美,但第二个返回错误比“helper.calc.add不是一个函数”。怎么了?JS。对象函数返回函数返回
例如第一:
var calc = (function() {
var add;
var remove;
// some functions add and remove...
return {
add: add,
remove: remove
}
})();
calc.add(1);
其次:
var helper = (function() {
return {
calc: function() {
var add;
var remove;
// some functions add and remove...
return {
add: add,
remove: remove
}
}
}
})();
helper.calc.add(1);
在控制台:
1
Uncaught TypeError: helper.calc.add is not a function
答
helper.calc
是function
,而不是object
调用function
来访问函数返回的对象的属性。
var handler = 1;
var calc = (function() {
var add;
var remove;
if (handler > 0) {
add = function(a) {
console.log(a++);
};
remove = function(a) {
console.log(a--);
};
} else {
add = function(a) {
console.log(a += 2);
};
remove = function(a) {
console.log(a -= 2);
};
}
return {
add: add,
remove: remove
}
})();
var helper = (function() {
return {
calc: function() {
var add;
var remove;
if (handler > 0) {
add = function(a) {
a++;
};
remove = function(a) {
a--;
};
} else {
add = function(a) {
a += 2;
};
remove = function(a) {
a -= 2;
};
}
return {
add: add,
remove: remove
}
}
}
})();
calc.add(1);
helper.calc().add(1);
答
我
modified
您的console.log显示最终结果。你是 错误地将calc
解释为object
,它是function
。 二是 的ES6方法,你可以用它来从一个函数返回的对象
它将重组中添加或删除对象,它是反向于ES6解构。
return { add, remove }
相当于
return { add : add, remove: remove }
var handler = 1;
var calc = (function() {
\t var add;
var remove;
\t if (handler > 0) {
add = function (a) {
console.log('calc add ' , ++a);
} ;
remove = function (a) {
console.log(a--);
};
} else {
add = function (a) {
console.log(a += 2);
};
remove = function (a) {
console.log(a -= 2);
};
}
return { add, remove }
})();
var helper = (function() {
\t return {
\t calc: function() {
\t var add;
var remove;
if (handler > 0) {
\t add = function (a) {
\t console.log('Helper calc add ', ++a);
};
remove = function (a) {
\t a--;
};
} else {
\t add = function (a) {
\t a += 2;
};
remove = function (a) {
\t a -= 2;
};
}
return { add , remove }
}
}
})();
calc.add(1)
helper.calc().add(1)
'helper.calc'是'function',不'object' ...尝试'helper.calc() .add(1);' – Rayon
您可能打算立即调用函数'calc'。 – RemcoGerlich