Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

require() turns constructor's functions to prototypes?

require() turns constructor's functions to prototypes?

Problem

There is just one behavior of javascript or specifically node.js' require() that I like to understand. I already read this:

Adding new properties to constructor Function without .prototype

and this:

The difference between putting functions into an object and prototyping them?

But if you use require() http://docs.nodejitsu.com/articles/getting-started/what-is-require to create new object like:

var Ftp = require("jsftp"),
    ftp = new Ftp({
      host: "ftp.mywebsite.com",
    });

And then let say if you do ftp.getPutSocket() later, it's actually calling the original Ftp.getPutSocket = function() {} in jsftp.js file.

Now how could it be? I thought if you do new Something(), you can only call into Ftp.prototype.getPutSocket. So did require() did some magic here?

UPDATE 1:

So it's nothing to do with require() but basically a function.call(Ftp.prototype) line that the end. But how come this gave me error:

http://jsfiddle.net/qhoc/7j3Vp/

var Test = function() {
    console.log('aa');
}

(function() {
    this.anotherTest = function() {
        console.log('bb');
    }
}).call(Test.prototype);

Error:

Uncaught TypeError: Cannot read property 'prototype' of undefined 

I tried to do the same thing as https://github.com/sergi/jsftp/blob/master/lib/jsftp.js

Problem courtesy of: HP.

Solution

When getPutSocket is defined (https://github.com/sergi/jsftp/blob/master/lib/jsftp.js#L620), this is actually Ftp.prototype (see https://github.com/sergi/jsftp/blob/master/lib/jsftp.js#L803).

So it doesn't look like Ftp.getPutSocket is defined at all. It is only defined on Ftp.prototype.

Update 1:

This fails because of the order in which javascript evals things. Functions first, then variable assignments.

This however, works:

function Test() {
    console.log('aa');
}

(function() {
    this.anotherTest = function() {
        console.log('bb');
    }
}).call(Test.prototype);
Solution courtesy of: Pascal Belloncle

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

require() turns constructor's functions to prototypes?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×