blog
My other blog
e builds an object named
deep_thought
, sets its the_answer
property to 42, and creates an ask_question
method. When deep_thought.ask_question()
is executed, JavaScript establishes an execution context for the function call, setting this
to the object referenced by whatever came before the last ”.”, in this case: deep_thought
. The method can then look in the mirror via this
to examine its own properties, returning the value stored in this.the_answer
: 42. Constructor Likewise, when defining a function to be used as a constructor with the new
keyword, this
can be used to refer to the object being created. Let’s rewrite the example above to reflect that scenario:
Instead of explicitly creating the deep_thought
object, we’ll write a function to create BigComputer
objects, and instantiate deep_thought
as an instance variable via the new
keyword. When new BigComputer()
is executed, a completely new object is created transparently in the background. BigComputer
is called, and its this
keyword is set to reference that new object. The function can set properties and methods on this
, which is transparently returned at the end of BigComputer
’s execution.
0 Comments:
Post a Comment
<< Home