Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  2] [ 2]  / answers: 1 / hits: 47868  / 13 Years ago, fri, august 12, 2011, 12:00:00

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



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


What gives?



I refuse to use two plain vars in succession, because I'm trying to get nice code out of JS.



Update:



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/


More From » object

 Answers
95
// Your code
var wF = {
w : 560,
h : (312 - 42) / (560 / this.w) + 42
};





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.



(And so this.w, whatever this is, is likely undefined. Dividing by undefined yields NaN.)



So then you might try:



// Let's not use `this`
var wF = {
w : 560,
h : (312 - 42) / (560 / wF.w) + 42
};





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.






Solution



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;

[#90643] Thursday, August 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rociom

Total Points: 287
Total Questions: 88
Total Answers: 101

Location: Oman
Member since Wed, Nov 17, 2021
3 Years ago
;