2011-05-27 28 views
0

这里是为什么“这”始终是在原型窗口的JavaScript类

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,当我跑这个代码代码:

​​

令我惊讶它是未定义的。在检查时,似乎this指的是全局对象窗口。现在什么这里发生了:( 我预计this._weight指人从粗略计算物品重量,否则,这应该有被称为解剖最少,因为它是一个对象。可能有人澄清疑问

回答

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

我不知道这是不是最好的解决办法,但它的我现在能想到的最好的。

+0

显然明白,不能从我上面所解释的完成。那么应该怎么做?这不是最好的回答被投票 – Deeptechtons 2011-05-27 06:23:24

+0

@deeptechtons,我编辑答案提供一个替代。看到这里还有一个工作jsfiddle:http://jsfiddle.net/C3puH/ – 2011-05-27 06:29:21

+0

你赢得了比赛,感谢那整洁的代码 – Deeptechtons 2011-05-27 06:44:11

0

这没有什么与原型做。

当您在浏览器中工作时,您的上下文(this)被设置为window对象。这使您可以拨打setTimeoutalert等。就好像它们是全球功能一样。即任何你的脚本都是全局的window对象的一种方法。

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

+0

为什么是这样的,都有相同的答案!所以我应该怎么做的东西工作,因为我期望包装内关闭 – Deeptechtons 2011-05-27 06:25:51

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

所以你建议与人类做什么来获得我想要的结果 – Deeptechtons 2011-05-27 06:25:02

+0

@deeptechtons我不知道为什么你要添加功能的原型,因为你将用新的方式创建对象。将上面的例子添加。 – 2011-05-27 06:27:11

+0

我不明白,原型是专为此目的而设计的?我错过了什么 – Deeptechtons 2011-05-27 06:31:31

相关问题