为什么没有定义变量?

时间:2014-11-29 05:54:42

标签: javascript

这里调用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();

这没关系,抱歉我的英语不好。

2 个答案:

答案 0 :(得分:1)

这里:

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

square.calcArea();member/methodobject only可以访问second one这就是为什么它在this工作的地方不起作用,因为你正在使用{ {1}} 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访问的值。

答案 1 :(得分:0)

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