gpt4 book ai didi

javascript - 混淆了js中的变量

转载 作者:行者123 更新时间:2023-11-29 10:41:32 25 4
gpt4 key购买 nike

function Person(name){
var age;
this.name = name;
this.setAge = function(a){
age = a;
}
this.getAge = function(){
return age;
}
}
var p0 = new Person("John");
p0.setAge(24);
console.log("p0.getAge "+p0.getAge());//p0.getAge 24
var p1 = new Person("Mike")
p1.setAge("25");
console.log("p0.getAge "+p0.getAge());//I think the output here should be p0.getAge 25,but it is p0.getAge 24
console.log("p1.getAge "+p1.getAge());//p0.getAge 25

变量“age”不属于Person的任何实例,因为Person的构造函数中没有“this.age”,最初应该由Person的实例共享,但结果不是我所期望的.我很困惑!

最佳答案

function Person(name){
var age;
this.name = name;
this.setAge = function(a){
age = a;
}
this.getAge = function(){
return age;
}
}

var age;,你没有声明this.age,当你不希望从外部直接访问变量时,特别是这样做,即你试图将其设为私有(private)对于该对象,这就是为什么您不为该对象创建一个属性,而只是为该闭包创建一个变量。

您仍然可以在对象内部访问它并使用 getAge 方法返回它,但不能直接使用年龄。所以没有属性age,但是有一个变量age

关于javascript - 混淆了js中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28105909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com