Javascript 未定义变量/参数

Javascript 未定义变量/参数,javascript,constructor,Javascript,Constructor,功能用户(姓名1、年龄、国家){ this.name1=name1; 这个。年龄=年龄; 这个国家=国家; } user.prototype.yourName=函数(){ log(`您的名字是${name1}`); } user.prototype.yourAge=函数(){ log(`您的年龄是${Age}&您的年龄以天为单位是${Age*365}`); } user.prototype.yourCountry=函数(){ log(`您的国家是${Country}`); } 让firstUse

功能用户(姓名1、年龄、国家){
this.name1=name1;
这个。年龄=年龄;
这个国家=国家;
}
user.prototype.yourName=函数(){
log(`您的名字是${name1}`);
}
user.prototype.yourAge=函数(){
log(`您的年龄是${Age}&您的年龄以天为单位是${Age*365}`);
}
user.prototype.yourCountry=函数(){
log(`您的国家是${Country}`);
}
让firstUser=new user('Any Name'、'Any Age'、'Any Country');
firstUser.yourName()//名称1未定义
firstUser.yourAge()//年龄没有定义

firstUser.yourCountry()//未定义国家/地区
在变量之前添加this关键字,以引用调用该方法的对象的实例变量

功能用户(姓名1、年龄、国家){
this.name1=name1;
这个。年龄=年龄;
这个国家=国家;
}
user.prototype.yourName=function(){
log(`您的名字是${this.name1}`);
}
user.prototype.yourAge=function(){
log(`您的年龄是${this.Age}&您的年龄(天)是${this.Age*365}`);
}
user.prototype.yourCountry=函数(){
log(`Your Country是${this.Country}`);
}
让firstUser=newuser('anyname',20,'anycountry');
firstUser.yourName()//名称1未定义
firstUser.yourAge()//年龄没有定义

firstUser.yourCountry()//未定义国家/地区
您正在使用Javascript中的原型

所以prototype允许您在vanila javascript中使用面向对象的语法,您可以在其中继承构造函数的属性和方法

那么你的情况呢

function user(name1,age,country){
    this.name1=name1;
    this.age=age;
    this.country=country;
}
user
方法中定义了
constructor()
,因此需要访问方法
user.prototype.yourName
中的值。因此,您需要使用
this
继承构造函数的属性,因为
user.prototype.yourName
将有自己的作用域

user.prototype.yourName=function(){
    console.log(`Your Name Is ${this.name1}`);
}
user.prototype.yourAge=function(){
    console.log(`Your Age Is ${this.age} & Your Age In Days Is ${this.age*365}`);
}
user.prototype.yourCountry=function(){
    console.log(`Your Country Is ${this.country}`);
}

使用
this.name1
this.age
this.country
打印数据