我有一个简单的问题,但我无法理解。
<script type="text/javascript">
var man = function(){
var age = 1;
this.shoes = 2;
};
man.prototype = {
create: function(){
//age = 5;
console.log(age);
console.log(this.shoes);
}
}
var man1 = new man;
man1.create();
</script>
-好吧,我创建了一个有 2 个变量的男人,年龄和鞋子。我只在鞋子中使用“this”。在我在 man 中构建了一个方法原型(prototype)之后。
-如果我执行此代码,首先 console.log 会告诉我:
Uncaught ReferenceError :年龄未定义(逻辑)
第二个控制台是“2”(正确)。
-如果我写:console.log(this.age),则消息错误为:未定义。
-但是如果我在新方法中输入年龄值 (age=5)(不使用“var”来创建 var),它就会起作用。
如果我在阅读此内容之前输入了值,为什么我只能使用age var?
最佳答案
age 变量位于“constructors”闭包内,这使得它只能在“constructors”闭包中使用。您可以在该函数(闭包)内部使用年龄变量,但不能在外部使用。
如果您想让它可以从外部访问,请将其添加到此或创建一个 getter 函数,例如:
var man = function(){
var age = 1;
this.shoes = 2;
this.getAge = function() { return age; };
};
但是如果你没有在函数内部声明变量,但仍然设置它,那么它将在浏览器窗口
中的全局对象上定义。这不会使年龄在 man 对象上可用,但您可以在任何地方访问它。这里需要澄清一下:
function tellAgeDelayedGlobal() {
age = 1;
setTimeout(function() { console.log(age) }, 1000);
}
function tellAgeDelayedDeclared() {
var age = 1;
setTimeout(function() { console.log(age) }, 1000);
}
tellAgeDelayedGlobal();
tellAgeDelayedDeclared();
age = 2;
这将打印到控制台:
2
1
关于javascript - 原型(prototype)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018167/