“这个"内部对象 [英] "this" inside object
问题描述
我正在尝试根据通过请求传入的宽度(默认为 560)计算比例高度(同时不包括静态高度元素).
I'm trying to calculate a proportional height (while excluding a static height element) from a width that gets passed in via a request (defaults to 560).
然而,wF.h
的计算结果为 NaN
.如果我将 this.w
替换为 560 它可以工作,但在尝试引用 wF
的 w
属性时无效.
However, wF.h
evaluates to NaN
. If I replace this.w
with 560 it works, but not when trying to reference the w
property of wF
.
var wF = {
w : 560,
h : (312 - 42) / (560 / this.w) + 42
};
是什么?
我拒绝连续使用两个普通变量,因为我试图从 JS 中获得漂亮的代码.
I refuse to use two plain vars in succession, because I'm trying to get nice code out of JS.
更新:
感谢所有帮助解释和解决我的问题的人.我想我只能习惯了.我将分阶段设置该对象以继续该项目,尽管它仍然让我有点恼火;).我为任何偶然发现类似问题的人找到并阅读了一篇关于该主题的好文章:http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
Thanks to everyone who helped explain and solve my problem. I guess i'll just have to get used to that. I'll be setting the object up in stages to get on with the project, even though it still annoys me slightly ;). I found and read a nice article on the topic for anyone who stumbles upon similar issues: http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
推荐答案
// Your code
var wF = {
w : 560,
h : (312 - 42) / (560 / this.w) + 42
};
<小时>
这个
不是你想的那样
Javascript 没有块作用域,只有函数作用域:wF
定义中的this
是否not 引用wF代码>.
this
isn't what you think it is
Javascript has no block scope, only function scope: this
inside the definition for wF
does not refer to wF
.
(所以 this.w
,无论 this
是什么,很可能是 undefined
.除以 undefined
产生NaN
.)
(And so this.w
, whatever this
is, is likely undefined
. Dividing by undefined
yields NaN
.)
那么你可以试试:
// Let's not use `this`
var wF = {
w : 560,
h : (312 - 42) / (560 / wF.w) + 42
};
<小时>
你还没有完成定义对象
但是,您仍在定义对象,您尝试在其中使用 wF.w
:还没准备好.
You haven't finished defining the object yet
However, you're still defining the object where you attempt to use wF.w
: it's not ready for that yet.
所以,是的,您必须使用两个变量...或分阶段设置对象:
So, yes, you will have to use two variables... or set up the object in stages:
// We can't even use `wF`; split up the property definitions
var wF = {};
wF.w = 560;
wF.h = (312 - 42) / (560 / wF.w) + 42;
这篇关于“这个"内部对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!