javascript – Why won’t this object’s prototype’s init function run – Education Career Blog

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?

,

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.

,

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.

Leave a Comment