我正在使用各种书籍学习 javascript,但我注意到我找不到关于何时使用 return 的充分解释。我知道当你想从函数返回一个值时你会使用它,但是有来自 Javascript 的例子:The Good Parts:
var quo = function(status) {
return {
get_status: function() {
return status;
}
};
};
var myQuo = quo("amazed");
document.writeln(myQuo.get_status());
当 quo 函数作为参数已经可用时,为什么必须返回状态?换句话说,为什么只是
return {
get_status: status;
}
不工作?
紧随其后的页面上的另一个示例:
var add_the_handlers = function(nodes) {
var helper = function(i) {
return function(e) {
alert(i);
};
};
var i;
for (i = 0; i<nodes.length; i+=1) {
nodes[i].onclick = helper(i);
}
};
为什么我们要在函数中返回 alert(i) 而不是简单地放置 alert(i)?
最佳答案
return {
get_status: status
}
不会定义一个 getter,它是一个返回基础值的函数。它只会定义一个属性。
你会用它作为
var status = quo.get_status;
任何用户都可以更改状态
quo.get_status = 'new status directly changed';
使用的原因之一
return {
get_status: function() {
return status;
}
};
是它使 status
私有(private):quo
对象的用户不能更改 的内部
对象,他们只能用status
属性quo
var status = quo.get_status();
关于javascript - 何时在 javascript 中使用 'return',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899313/