views:

43

answers:

2

I use the following function for creating new objects.

function newObj(o) {
 var params = Array.prototype.slice.call(arguments,1);
 function F() {}
 F.prototype = o;
 var obj = new F();
 if(params.length) {
  obj.init.apply(obj,params);
 }
 return obj;
} 

And it works well most of the time. However one of my base "classes" is now defined as inheriting from another base class

SPZ.EditablePuzzle = function () {
    // function and variable definitions

    return {
       ///some methods and properties
    }
}();

SPZ.EditablePuzzle.prototype = SPZ.Puzzle;

Now when I use newObj() to create a new SPZ.EditablePuzzle the init function is not defined even though it is defined in SPZ.Puzzle and I make sure EditablePuzzle runs after Puzzle

Why won't my newObj function find the init function? Shouldn't it automatically look in the prototype as soon as it fails to find it in the object itself?

A: 

Concerning the problem:

function Foo() {
}

Foo.prototype.init = function() {
    console.log('bla');
};


function FooBar() {
}

FooBar.prototype = Foo; // looks fishy...

var kitten = new FooBar();

console.log(kitten.init); // yields undefined, uh what?

The problem is, that in this case Foo itself gets assigned to the prototype property, when in fact you wanted to do:

FooBar.prototype = Foo.prototype

See the difference? Foo has no init property as it is defined on the prototype object.

Ivo Wetzel
The () is there so the function gets called immediately to return the object. And in my case the object i'm inheriting from does have init as a direct property
wheresrhys
Ah, yeah now I see it, sorry 'bout that still a bit early in the morning here ;)
Ivo Wetzel
A: 

I suspect the inheritance is not well set. try doing

SPZ.EditablePuzzle.prototype = new SPZ.Puzzle;

Might solve this problem, though I am not sure.

araf3l
Looks liek that's it. Cheers
wheresrhys