function user(name1, age, country) {
this.name1 = name1;
this.age = age;
this.country = country;
}
user.prototype.yourName = function() {
console.log(`Your Name Is ${name1}`);
}
user.prototype.yourAge = function() {
console.log(`Your Age Is ${age} & Your Age In Days Is ${age*365}`);
}
user.prototype.yourCountry = function() {
console.log(`Your Country Is ${country}`);
}
let firstUser = new user('Any Name', 'Any Age', 'Any Country');
firstUser.yourName(); //name1 Is Not Defined
firstUser.yourAge(); //age Is Not Defined
firstUser.yourCountry(); //country Is Not Defined
我不知道问题出在哪里!它一直在说name1或年龄或国家没有定义...
发布于 2021-01-15 15:04:09
在变量前添加this关键字,以引用调用该方法的对象的实例变量
function user(name1,age,country){
this.name1=name1;
this.age=age;
this.country=country;
}
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}`);
}
let firstUser=new user('Any Name', 20 ,'Any Country');
firstUser.yourName();//name1 Is Not Defined
firstUser.yourAge();//age Is Not Defined
firstUser.yourCountry();//country Is Not Defined
发布于 2021-01-15 15:16:22
您正在使用Javascript中的prototype
所以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}`);
}https://stackoverflow.com/questions/65731752
复制相似问题