Hello,
I have a question about how prototyping relates to variables and their
scope.
Given the following code:
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
var ParentObject = function()
{
var objectName = "ParentObje ct";
this.getObjectN ame = function()
{
return objectName;
}
this.setObjectN ame = function( newObjectName )
{
objectName = newObjectName;
}
}
var ChildObject = function()
{
ParentObject.ap ply(this, arguments);
this.tryToRefer enceObjectNameV ar = function()
{
var text = null;
// Attempt to reference the variable "objectName ",
// which was created in ParentObject.
try
{
text = "ChildObjec t's \"objectName \"" +
" variable is \"" + objectName + "\"";
}
catch( error )
{
alert( "Error: " + error.name +
" at " + "line: " + error.lineNumbe r + "\n" +
"\"" + error.message + "\"\n" +
"Stack:\n" + error.stack + "\n" );
}
return text;
}
}
var child = new ChildObject();
child.tryToRefe renceObjectName Var();
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
The last call throws this ReferenceError:
Error: objectName is not defined
Is this because prototyping, which I have done by calling the "apply"
method of a constructor, creates an independent execution context
that cannot be accessed from the "child" object's execution context? In
other words,
when I call
child.getObject Name();
child.tryToRefe renceObjectName Var();
are two (or several) different execution contexts being referenced? How is
the
JavaScript interpreter handling this?
TIA,
Greg
I have a question about how prototyping relates to variables and their
scope.
Given the following code:
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
var ParentObject = function()
{
var objectName = "ParentObje ct";
this.getObjectN ame = function()
{
return objectName;
}
this.setObjectN ame = function( newObjectName )
{
objectName = newObjectName;
}
}
var ChildObject = function()
{
ParentObject.ap ply(this, arguments);
this.tryToRefer enceObjectNameV ar = function()
{
var text = null;
// Attempt to reference the variable "objectName ",
// which was created in ParentObject.
try
{
text = "ChildObjec t's \"objectName \"" +
" variable is \"" + objectName + "\"";
}
catch( error )
{
alert( "Error: " + error.name +
" at " + "line: " + error.lineNumbe r + "\n" +
"\"" + error.message + "\"\n" +
"Stack:\n" + error.stack + "\n" );
}
return text;
}
}
var child = new ChildObject();
child.tryToRefe renceObjectName Var();
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
The last call throws this ReferenceError:
Error: objectName is not defined
Is this because prototyping, which I have done by calling the "apply"
method of a constructor, creates an independent execution context
that cannot be accessed from the "child" object's execution context? In
other words,
when I call
child.getObject Name();
child.tryToRefe renceObjectName Var();
are two (or several) different execution contexts being referenced? How is
the
JavaScript interpreter handling this?
TIA,
Greg
Comment