user656925
user656925

Reputation:

Accessing context property of a function object | How to?

Each function object should have two "hidden" properties ( per JavaScript The Good Parts, The Functions Chapter )

context

and

code

Is there a way to access these properties?

Upvotes: 1

Views: 691

Answers (1)

raina77ow
raina77ow

Reputation: 106375

Well, you can access the function code pretty easily - by using toString() (or Mozilla's non-standard toSource()):

var x = function() { alert('Here is my happy function'); };
console.log(x.toString());

As for context, I suppose DC meant more than simple this, and actually wrote about Execution Context.

UPDATE: Have found an interesting snippet in ES5 specification, where these two properties are actually described in some details - and not as abstract concepts:

13.2 Creating Function Objects

Given an optional parameter list specified by FormalParameterList, a body specified by FunctionBody, a Lexical Environment specified by Scope, and a Boolean flag Strict, a Function object is constructed as follows:

...

Set the [[Scope]] internal property of F to the value of Scope.

...

Set the [[Code]] internal property of F to FunctionBody.

At the same time:

Lexical Environments and Environment Record values are purely specification mechanisms and need not correspond to any specific artefact of an ECMAScript implementation. It is impossible for an ECMAScript program to directly access or manipulate such values.

So I guess that closes the question about accessing Scope property of function.

As for Code property, its read-only accessing with toString(), as was rightly noticed by Matt, is implementation-dependent - yet is more often implemented than not. )

Upvotes: 2

Related Questions