View Single Post
Old 11-04-2010, 10:43 PM   PM User | #1
johnmerlino
Regular Coder

 
Join Date: Oct 2009
Posts: 189
Thanks: 38
Thanked 3 Times in 3 Posts
johnmerlino is an unknown quantity at this point
simulating classes in JavaScript

Hey all,

I am reading a book called JavaScript patterns. In it, this method is created:
Code:
var klass = function(Parent,template){
	var Child, F, i;
	
	Child = function () {
		if (Child.uber && Child.uber.hasOwnProperty("__construct")) {  
			Child.uber.__construct.apply(this, arguments);
		}
		if (Child.prototype.hasOwnProperty("__construct")) {
			Child.prototype.__construct.apply(this, arguments);
		}
	}
	
	Parent = Parent || Object;  
	
	F = function () {};
	F.prototype = Parent.prototype;
	Child.prototype = new F(); 
	Child.uber = Parent.prototype;  
	Child.prototype.constructor = Child;


	for (i in template) {
		if (template.hasOwnProperty(i)) {
			Child.prototype[i] = template[i];
		}
	}
	return Child;
}
Does anyone have an understanding of why we instantiate a new F() to the Child prototype rather than instantiate the Parent prototype? As you can see above, we assign Parent prototype to F prototype and then instantiate F() object to Child prototype. I'm not sure why it's being done this way.

Code:
	F.prototype = Parent.prototype;
	Child.prototype = new F();
Thanks for response.
johnmerlino is offline   Reply With Quote