下面的程序名称 属性 是否可以直接通过 me.name 对象更改?
Below program's name property can be changed directly thru me.name object or not?
let me = {
name: "Sina",
talk: ()=>
{
return this.name;
},
setName: (newName)=>
{
this.name = newName;
}
}
<console.log(me.name); //accessing directly thru object output: Sina>
<console.log(me.talk()); //accessed thru function, output: undefined. **Why undefined???????**>
<me.setName("Reena"); //passing argument to setName()>
<console.log(me.talk()); //output: Reena>
<me.name = "Beena"; // can be changed name property directly like this?>
< //**if so, why not displaying Beeba instead of Reena?????**>
<console.log(me.talk()); //**output: Reena not Beena. why???**>
输出:
Sina
undefined
Reena
Reena>
因为你用了箭头函数,但是他们没有this.
因此,如果您像此处那样更改代码,它将起作用:
let me = {
name: "Sina",
talk: function() {
return this.name;
},
setName: function(newName) {
this.name = newName;
}
}
me.setName("Reena");
console.log(me.talk());
me.name = "Beena";
console.log(me.talk());
尝试通过阅读这篇文章来了解有关箭头函数的更多信息:
Arrow functions
希望对你有所帮助:)
let me = {
name: "Sina",
talk: ()=>
{
return this.name;
},
setName: (newName)=>
{
this.name = newName;
}
}
<console.log(me.name); //accessing directly thru object output: Sina>
<console.log(me.talk()); //accessed thru function, output: undefined. **Why undefined???????**>
<me.setName("Reena"); //passing argument to setName()>
<console.log(me.talk()); //output: Reena>
<me.name = "Beena"; // can be changed name property directly like this?>
< //**if so, why not displaying Beeba instead of Reena?????**>
<console.log(me.talk()); //**output: Reena not Beena. why???**>
输出:
Sina
undefined
Reena
Reena>
因为你用了箭头函数,但是他们没有this.
因此,如果您像此处那样更改代码,它将起作用:
let me = {
name: "Sina",
talk: function() {
return this.name;
},
setName: function(newName) {
this.name = newName;
}
}
me.setName("Reena");
console.log(me.talk());
me.name = "Beena";
console.log(me.talk());
尝试通过阅读这篇文章来了解有关箭头函数的更多信息: Arrow functions
希望对你有所帮助:)