This question already has an answer here:
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/
this
isn't what you think it isJavascript has no block scope, only function scope:
this
inside the definition forwF
does not refer towF
.(And so
this.w
, whateverthis
is, is likelyundefined
. Dividing byundefined
yieldsNaN
.)So then you might try:
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:
The
this
keyword refers to the calling context, not an object.You need to do this in two steps like so:
You don't need to wrap the {...} in an Object(). It is already an object literal.
this
doesn't operate inside the object literal, it will point to the object that the function is currently running in so:will cause
this
to point to thewindow
object.EDIT: Previous code was not intended to be an answer, just a demonstration of what
this
is. Another possiblity would be to use a function that takes the width as an argument:Hi just redefine your second property as a function object and it will work. I think it is possible to access the context of the calling object from within a function
When you use this in a JSON object declaration, it points to the current instance.
You can try this code in your console to understand it better: