【问题标题】:Why is 'this' always a Window in a prototype for Javascript Classes为什么'this'总是Javascript类原型中的一个窗口
【发布时间】:2011-05-27 06:09:10
【问题描述】:

这里是代码

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,因为它是一个对象。有人可以澄清疑问

【问题讨论】:

    标签: javascript object window this prototype-programming


    【解决方案1】:

    你不能那样做。 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);
    }
    

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

    【讨论】:

    • 显然明白,从我上面解释的内容中是无法做到的。那么应该怎么做呢?这不是要投票的最佳答案
    • @Deeptechtons,我编辑了答案以提供替代方案。另请参阅此处的工作 jsfiddle:jsfiddle.net/C3puH
    【解决方案2】:

    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
            })
        }
    }
    

    【讨论】:

    • 那么你建议用 person 类做什么来得到我想要的结果
    • @Deeptechtons 我不确定你为什么要向原型中添加函数,因为无论如何你都要用 new 创建对象。将在上面添加示例。
    • 我不明白,原型就是为此目的设计的,对吧?我错过了什么
    • @Deeptechtons 我不知道你的目的是什么,或者它与原型有何关系。也许您可以更清楚地了解您要做什么以及它需要如何直接修改原型属性?
    【解决方案3】:

    这与原型无关。

    当您在浏览器中工作时,您的上下文 (this) 设置为 window 对象。这允许您致电setTimeoutalert 等。就好像它们是全局函数一样。 IE。您的任何脚本都是全局window 对象的方法。

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

    【讨论】:

    • 为什么会这样,答案都一样!!所以我应该怎么做才能让事情像我预期的那样工作在封闭内
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2015-05-08
    • 2010-10-07
    相关资源
    最近更新 更多