为什么'this'始终是Javascript类原型中的Window

时间:2011-05-27 06:09:11

标签: javascript object window this prototype-programming

这是代码

function Person(name, age, weight) {
    this._name = name;
    this._weight = weight;
    this._age = age;
}

Person.prototype = {
    Anatomy: {
        Weight: this._weight,
        Height: (function () {
            //calculate height from age and weight
        })
    }
}

当我运行此代码时,我预计Anatomy.weight为60:

var x = new Person('jack',24,60);
console.dir(x.Anatomy);

令我惊讶的是它未定义。在检查时,似乎this指的是全局对象窗口。现在这里发生了什么:( 我希望this._weight能够引用Person对象的权重,否则从粗略计算中,至少应该参考Anatomy,因为它是一个对象。有人可以澄清疑问吗

3 个答案:

答案 0 :(得分:4)

你不能那样。 this仅适用于函数。在使用它的地方,它指的是全局对象。一个可能的解决方案是:

function Anatomy(weight) {
    this.Weight = weight;
    this.Height = [...];
}

function Person(name, age, weight) {
    this._name = name;
    this._weight = weight;
    this._age = age;
    this.Anatomy = new Anatomy(this._weight);
}

我不知道这是否是最好的解决方案,但这是我现在能想到的最好的解决方案。

答案 1 :(得分:1)

this根据范围进行更改,范围仅受函数影响。因此,由于Person.prototype只是一个不在函数中的对象,this指的是全局对象,在浏览器中往往是window

编辑:示例修复

function Person(name, age, weight) {
    this._name = name;
    this._weight = weight;
    this._age = age;
    this.Anatomy: {
        Weight: this._weight,
        Height: (function () {
            //calculate height from age and weight
        })
    }
}

答案 2 :(得分:0)

这与原型无关。

在浏览器中工作时,您的上下文(this)设置为window个对象。这允许您致电setTimeoutalert等。好像它们是全球功能。即您的任何脚本都是全局window对象的方法。

在其他Javascript主机中不是这样,例如在node.js。