Javascript "this" 问题
Javascript "this" issue
我是 Javascript 的新手,想弄清楚为什么 console.log 没有打印出用户名。我希望函数 NewUser 获取新变量(Emily 和 Jason)并打印出他们的名字以及他们的 "life"。
我的问题似乎是行 "this.name="" ",我不知道如何让 this.name 接受新用户的变量名称。我试过了 this.name;但返回未定义。
function NewUser(){
this.name="";
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser();
Jason.name="Jason";
var Emily=new NewUser();
Emily.name="Emily";
您只需在函数中添加一个参数,如下所示:
function NewUser(name){
this.name=name;
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser("Jason");
var Emily=new NewUser("Emily");
因为调用构造函数时正在执行console.log语句,此时name变量为空字符串
var Jason=new NewUser(); // console.log called here
Jason.name="Jason";
var Emily=new NewUser(); // console.log called here
Emily.name="Emily";
要解决此问题,请尝试将用户名传递到函数中:
function NewUser(username){
this.name=username;
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser("Jason");
var Emily=new NewUser("Emily");
您正在阅读 this.name
,然后再写入任何内容。
另一种方法是创建一个 log
函数供您稍后调用。示例:
function NewUser(){
this.name="";
this.life=100;
this.mana=1000;
this.log = function() {
console.log(this.life);
console.log(this.name);
}
}
var Jason=new NewUser();
Jason.name="Jason";
var Emily=new NewUser();
Emily.name="Emily";
Jason.log();
Emily.log();
我是 Javascript 的新手,想弄清楚为什么 console.log 没有打印出用户名。我希望函数 NewUser 获取新变量(Emily 和 Jason)并打印出他们的名字以及他们的 "life"。
我的问题似乎是行 "this.name="" ",我不知道如何让 this.name 接受新用户的变量名称。我试过了 this.name;但返回未定义。
function NewUser(){
this.name="";
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser();
Jason.name="Jason";
var Emily=new NewUser();
Emily.name="Emily";
您只需在函数中添加一个参数,如下所示:
function NewUser(name){
this.name=name;
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser("Jason");
var Emily=new NewUser("Emily");
因为调用构造函数时正在执行console.log语句,此时name变量为空字符串
var Jason=new NewUser(); // console.log called here
Jason.name="Jason";
var Emily=new NewUser(); // console.log called here
Emily.name="Emily";
要解决此问题,请尝试将用户名传递到函数中:
function NewUser(username){
this.name=username;
this.life=100;
this.mana=1000;
console.log(this.life);
console.log(this.name);
}
var Jason=new NewUser("Jason");
var Emily=new NewUser("Emily");
您正在阅读 this.name
,然后再写入任何内容。
另一种方法是创建一个 log
函数供您稍后调用。示例:
function NewUser(){
this.name="";
this.life=100;
this.mana=1000;
this.log = function() {
console.log(this.life);
console.log(this.name);
}
}
var Jason=new NewUser();
Jason.name="Jason";
var Emily=new NewUser();
Emily.name="Emily";
Jason.log();
Emily.log();