tags:

views:

34

answers:

2

Hi,

I finished reading "Object Oriented Javascript". I'm following this code to "inherit" and object from another:

function deriveFrom(child,parent)
{
    if (parent == this)
        alert("You can't inherit from self class type")
    else
    {
        var f = function () { }
        f.prototype = parent.prototype;
        child.prototype = f;
        child.prototype._super = f.prototype;
        child.constructor = child;

    }
}

The problem I encountered, is when I want to access a function or var that is not defined in the child class, but it is in the parent class, and example:

Think that ClassB construction creates a var called myVar.

deriveFrom(ClassA,ClassB);
var obj=new ClassA();

This creates a prototype chain like this:

obj-> prototype (function)->prototype (ClassB) -> myVar.

If I do something like a.myVar I get an undefined. Why? The book states that javascript will look for the var through prototypes until it gets it. So, first it will search for it at obj, not found it will get its prototype object that it is a function, it won't find it, then it will continue going down into the function prototype, and there it will find myVar. Isn't this the process?

if I do obj.prototype.myVar it finds it :S.

Could anybody help please?

Thanks in advance, Mathew.

+1  A: 

Whenever you have a question about fundamental javascript design patterns like this, the first place to look is the great Douglas Crockford. In his article on prototypal inheritance he ultimately suggests the following solution:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

You could combine this solution with the type checking code in your current implimentation, though I'd say error checking may not be necessary if this is a convenience method for use in your own code.

Daniel Mendel
Then, with the patter you exposed, the look up of vars in all the "hierarchy" of prototypes will work?. Have to check it.
Mathew man
The code above should be a working replacement for the code in your original question, but that may or may not do what you're asking -- can you give a code example of the desired behavior?
Daniel Mendel
A: 
Mathew man