为什么它在情况1中抛出错误,而在情况2中没有?
案例1:
export class AppComponent implements OnInit{
obj={
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
Object.keys(this.obj).forEach(function(key)
{
console.log(key,this.obj[key])
}
)
}
}
}
错误:无法读取未定义的属性"obj">
案例2:
export class AppComponent implements OnInit{
ngOnInit() {
this.calling();
}
calling() {
if(true){
let obj={
name:"XYZ",
age:"22",
height:"5"
}
Object.keys(obj).forEach(function(key)
{
console.log(key,obj[key])
}
)
}
}
}
在这种情况下,控制台中不会显示任何错误。
使用function()
定义函数时,this
引用的值会发生更改。如果希望this
继续引用类,请使用箭头函数。
export class AppComponent implements OnInit {
obj = {
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
Object.keys(this.obj).forEach((key) =>
{
console.log(key, this.obj[key])
}
)
}
}
}
您也可以通过在函数上调用bind()
来修复此问题,以便在函数中设置this
。
export class AppComponent implements OnInit {
obj = {
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
const func = function(key) {
console.log(key, this.obj[key])
};
Object.keys(this.obj).forEach(func.bind(this));
}
}
}
您没有掌握Javascript中的作用域。
在第一个示例中,回调函数定义了自己的this
,因此外部函数this
是不可访问的。
为了解决这个问题,你可以使用箭头函数(或者你可以使用.bind(this)
,但我从来没有真正使用过(。
//arrow functinon
Object.keys(this.obj).forEach((key) => {
console.log(key,this.obj[key])
)}
以下是关于箭头函数与绑定的更多阅读:https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/
您的第二个示例之所以有效,是因为您用let
定义了obj
,所以它可以在您的函数中访问。
下面是一篇关于var/lit/const的好文章https://www.deadcoderising.com/2017-04-11-es6-var-let-and-const-the-battle-between-function-scope-and-block-scope/