为什么没有定义变量

Why the variable is not defined?

本文关键字:变量 定义 为什么      更新时间:2023-09-26

这里调用calcArea函数,函数作用域应该在它定义的作用域中,但是它的作用域有变量sideLength,为什么会出错?

var square = {
    sideLength: 6,
    calcArea: function () {
        console.log(sideLength * sideLength);
    }
};
square.calcArea();

你可以帮我吗?

var square = {
    sideLength: 6,
    calcArea: function () {
        console.log(this.sideLength * this.sideLength);
    }
};
square.calcArea();

没关系,对不起我的英语不好。

在这里:

var square = {
sideLength: 6,
calcArea: function () {
    console.log(sideLength * sideLength);
    }
}

square.calcArea();是一个member/methodobject only可以访问它,这就是为什么在这里它不起作用,因为它在second one中起作用,因为您使用this作为访问它的current object

var square = {
sideLength: 6,
calcArea: function () {
    console.log(this.sideLength * this.sideLength);
    }
}
square.calcArea();
 it works because you are using this.sideLength.

可以使用 console.log(square.sideLength); 查看 square.sideLength=6 访问的值。

示例中有三个作用域 - 全局作用域(包含控制台),对象作用域(包含sideLength和calcArea)和函数作用域(空)。 sideLength 是一个对象属性,变量 sideLength 未在函数作用域中定义。 您可以使用点表示法 (square.sideLength === 6) 访问对象属性,以及从对象内部(即,运行对象的方法时)通过特殊对象 "this" (this.sideLength === 6) 访问"同级"属性。