function createFunctionWithProperty(property) {
functionWithProperty.property = property;
return functionWithProperty;
function functionWithProperty() {
}
}
var a = createFunctionWithProperty(123);
var b = createFunctionWithProperty(321);
alert(a.property + " : " + b.property); // 123 : 321
据我所知,createFunctionWithProperty
和 functionWithProperty
都是函数声明,它们在任何 JavaScript 代码之前被提升、解析和引入。被执行。然而,在某些时候,在调用 createFunctionWithProperty 函数时,functionWithProperty 会变成一个闭包,这是一个非常特殊的 functionWithProperty 实例,它有自己的功能它所封闭的属性和变量每个实例都不同。这都是理论上的,但在这种情况下我不明白事情是如何运作的。有人会详细说明 functionWithProperty
何时以及如何成为闭包吗?谢谢。
最佳答案
在这种情况下,它是否是一个函数并不重要,更不用说是一个闭包,您可能已经这样做了:
function createObjectWithProperty(property) {
var objectWithProperty = {};
objectWithProperty.property = property;
return objectWithProperty;
}
var a = createObjectWithProperty(123);
var b = createObjectWithProperty(321);
alert(a.property + " : " + b.property);
关于javascript - 在这种特殊情况下,闭包是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915896/