Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite prototype chain

Tags:

javascript

Can anyone tell me why in this code:

var originalfunc = function() {
    this.run(this)
};

originalfunc.prototype.run = function(basefunc) {
    this.basefunc = basefunc;
    console.log(this);
};

var r = new originalfunc();

Produces a prototype chain that looks to be infinite:

enter image description here

Why is this happening? I know I'm assigning the originalfunc obj as a property of the run prototype but I'm only doing that once.

Working fiddle here:

http://jsfiddle.net/YmThL/

like image 268
Mike Rifgin Avatar asked Nov 20 '25 16:11

Mike Rifgin


1 Answers

You're setting this.basefunc to be a reference to the object referenced by this.

The constructor calls "run", passing the value this to it. At that point, this refers to the new object under construction. The "run" function sets the "basefunc" property on that same object (because this will also refer to it inside that call to "run") to the parameter, which was the object.

The effect is the same as if the constructor simply did:

this.basefunc = this;
like image 82
Pointy Avatar answered Nov 23 '25 04:11

Pointy