I've been reading up on scope chains and prototypes and although I've learned quite a bit I'm still confused by the following code examples. The first example, which was lifted from http://www.jibbering.com/faq/notes/closures/ works as expected; however, my attempt to rewrite it in a different form doesn't work as expected.
//Example 1: Code from the link - This Works As Expected
function objOne(param){
this.PropertyOne = param;
}
function objTwo(param){
this.PropertyTwo = param;
}
objTwo.prototype = new objOne("propertyOne");
var obj = new objTwo("propertyTwo");
alert(obj.PropertyOne); //result: propertyOne
alert(obj.PropertyTwo); //result: propertyTwo
//**********************************************************
//Example 2: My Attempt to Write it differently - Fails
//Problem: I thought the scope chain would work the same way for property three
var objThree = new Object();
objThree.PropertyThree = "propertyThree";
var objFour = new Object();
objFour.PropertyFour = "propertyFour";
objFour.prototype = objThree;
alert(objFour.PropertyThree); //result: undefined - I thought the scope chain would work the same here.
alert(objFour.prototype.PropertyThree); //result: propertyThree;
alert(objFour.PropertyFour); //result: propertyFour
So it is the 'undefined' for objFour.PropertyThree that puzzles me. I'd like to know WHY this works this way.
EDITED TO ADD: If you'd like to see an interesting illustration of the issue consider the following code. I put this together while working through examples and reading articles on the subject.
//**** Function Object vs. Instance Object
function Foo(){
this.something = "meh";
}
function ObjectsAndFunctions(){
//this is Foo as a function object and as such function properties are available.
alert(Foo.name); //result: Foo
alert(Foo.length); //result: 0
alert(Foo.something); //result: undefined
//this is Foo as an instance object so function properties are not available
var test = new Foo();
alert(test.name); //result: undefined
alert(test.length); //result: undefined
alert(test.something); //result: "meh"
}
When Foo is exposed as a function object you have function properties available (name, length) but instance properties are not available. When Foo is exposed as an instance object the function properties are gone and the object property (something) is available.
I doubt all of that is expressed exactly correctly; however, it does illustrate the problem (that is, my lack of understanding in the initial example) really well.