Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  144] [ 1]  / answers: 1 / hits: 28624  / 14 Years ago, thu, january 6, 2011, 12:00:00

I am trying to do something like this:



var obj = {
a: 5,
b: this.a + 1
}


(instead of 5 there is a function which I don't want to execute twice that returns a number)



I can rewrite it to assign obj.b later from obj.a, but can I do it right away during declaration?


More From » javascript

 Answers
14

No. this in JavaScript does not work like you think it does. this in this case refers to the global object.



There are only 3 cases in which the value this gets set:



The Function Case



foo();


Here this will refer to the global object.



The Method Case



test.foo(); 


In this example this will refer to test.



The Constructor Case



new foo(); 


A function call that's preceded by the new keyword acts as a constructor. Inside the function this will refer to a newly
created Object.



Everywhere else, this refers to the global object.


[#94347] Wednesday, January 5, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;