我是Javascript的新手,对闭包函数有疑问。
在下面的代码中,我创建了一个闭包函数,并为该函数设置了一个新的属性firstname。我希望标识创建的函数的属性- firstname,并使用代码- console.log(obj1.firstname);来显示它。
但由于某些原因,它显示为未定义。请让我知道问题出在哪里。
<html>
<head>
<script>
outerfunction = function(firstname,lastname) {
var innerfunction = function (sex) {
console.log(firstname);
console.log(lastname);
console.log(sex)
}
console.log('Initialize');
innerfunction.prototype.firstname = firstname;
return innerfunction;
}
obj1 = outerfunction('Bob','Mcdonald');
console.log(obj1.firstname);
obj2 = obj1('Male');
obj1 = outerfunction('Lucy','Mary');
obj1('Female');
</script>
</head>
<body>
This is the body
</body>
</html>发布于 2013-11-26 10:16:56
问题出在你使用prototype的时候。如果使用innerfunction.firstname = firstname;,应该可以解决未定义的问题。
outerfunction = function(firstname,lastname) {
var innerfunction = function (sex) {
console.log(firstname);
console.log(lastname);
console.log(sex)
}
console.log('Initialize');
innerfunction.firstname = firstname;
return innerfunction;
}
obj1 = outerfunction('Bob','Mcdonald');
console.log(obj1.firstname);
obj2 = obj1('Male');
obj1 = outerfunction('Lucy','Mary');
obj1('Female');发布于 2013-11-26 10:45:53
只需评论:
> outerfunction = function应该始终声明变量,特别是全局变量,这样它们就不会与具有相同名称或ID的DOM元素冲突(变量优先)。一旦声明了变量,就没有必要在声明可以执行的情况下赋值函数表达式(如果不做其他任何事情,它可以减少类型,但也可以在执行任何代码之前使函数可用,而不是在赋值时)。所以:
function outerfunction(firstname,lastname) { 形参列表中的项(名字、姓氏)被有效地声明为局部变量。所以对于内部函数
function innerfunction(sex) {
console.log(firstname);
console.log(lastname);
console.log(sex)此函数对outerfunction的名和姓有一个闭包。
> innerfunction.prototype.firstname = firstname;只有当innerfunction是一个构造函数,并且您希望实例继承firstname属性时,这才有用。函数不是从它们的公共原型继承的,而是从它们的私有[[Prototype]]继承的,这是它们构造时的构造函数的公共原型。
> obj1 = outerfunction('Bob','Mcdonald');这将返回一个innerfunction的“实例”,其中包含对名字和姓氏的闭包。
> console.log(obj1.firstname);但是firstname属性在obj1.prototype上(因为它就是在那里分配的),所以没有找到(请检查obj1.prototype.firstname)。
您混淆的部分原因可能是作用域链上的标识符解析(即变量firstname和lastname)与对象及其[[Prototype]]链上的对象属性解析(即继承和innerfunction.protoype.firstname)之间的差异。
https://stackoverflow.com/questions/20207239
复制相似问题