"这"内部对象 [英] "this" inside object

查看:98
本文介绍了"这"内部对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从通过请求传递的宽度计算比例高度(同时排除静态高度元素)(默认为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 。如果我用560替换 this.w ,它会起作用,但在尝试引用<$ c的 w 属性时则不行$ c> wF 。

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没有块范围,只有函数范围: this wF 的定义内是否参考 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 ,无论这个是什么,很可能 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 尚未做好准备

所以,是的,你必须使用两个变量......或者分阶段设置对象: / p>

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;

这篇关于&QUOT;这&QUOT;内部对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆