A function's this value is set either by how the function is called, or by using Function.prototype.bind.
Given:
function CL(){
console.log(this); // a new object
protoFunc(this); // protoFunc doesn't exist on CL's scope chain and will throw an error
}
If CL is called as follows (and assuming bind hasn't been used):
CL()
its this value has not been set, so on entering the function in non–strict mode it will be set to the global (window) object. In strict mode it will be undefined.
If CL is called using new:
var cl = new CL()
then this within the function will reference a new Object created as if by new Object()
, i.e. it's a reference to the instance. Since this new object is returned by default and here it is assigned to cl, then a reference to the constructor function's this has been kept, there is no need to keep any other reference.
Note that each call to CL creates an entirely new execution context.
If you create an instance of CL and then call a method assigned to the constructor's prototype like:
cl.protoFunc()
then this within protoFunc will be cl.
Your statement:
The function context before calling protoFunc is that of CL
doesn't make sense, presumably here you are confusing "context" with "this". As noted above, this is set by the call (or bind), so you have to show how you're calling CL to determine what ist this will be.
How do I get the function context into protoFunc
Given that this in the constructor is the instance and that a function's this value is set by the call:
cl.protoFunc()
will do the job.
Context
The term "context" has crept into ECMAScript jargon as a pseudonym for this, which is unfortunate. ECMA-262 defines execution context essentially as an environment created when entering a function (or a new global environment or when using eval) that includes the scope chain and all variables of the function, including its this value. You can't reference an execution context or access it in any way.
So a function's context is much more than just this.