首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >变量/参数未定义

变量/参数未定义
EN

Stack Overflow用户
提问于 2021-01-15 15:01:01
回答 2查看 38关注 0票数 0

代码语言:javascript
运行
复制
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或年龄或国家没有定义...

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-15 15:04:09

在变量前添加this关键字,以引用调用该方法的对象的实例变量

代码语言:javascript
运行
复制
    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

票数 1
EN

Stack Overflow用户

发布于 2021-01-15 15:16:22

您正在使用Javascript中的prototype

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

所以在你的情况下

代码语言:javascript
运行
复制
function user(name1,age,country){
    this.name1=name1;
    this.age=age;
    this.country=country;
}

在这里,在user方法中定义了constructor(),因此需要访问方法user.prototype.yourName方法中的值。因此,您需要继承使用this的构造函数的属性,因为user.prototype.yourName将拥有自己的作用域。

代码语言:javascript
运行
复制
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}`);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65731752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档