3

NEWBIE question.

I cannot access member function. What am I doing wrong?

index.js ->
var abc = require('./def');
var foo = new abc();
foo.zxc(); 

def.js ->
var bar = function(){
// do something
    var zxc = function(){
        // do something
    }
}
module.exports = def;

When I run in brwoser console it shows :

TypeError:foo.zxc is not a function

2 Answers 2

2

Because zxc is just a local variable not accessible from outside of the the bar function. You can change it to

var bar = function() {
   // do something
    this.zxc = function(){
        // do something
    }
}

Now, zxc is an own property of the constructed object so it will work.

Sign up to request clarification or add additional context in comments.

1 Comment

@kalpa are you sure that def.js is exporting function bar ? because it doesn't look like it in the code you posted…
0

Try something like the following:

// index.js ->
var abc = require('./def');
var foo = new abc.bar();
foo.zxc(); 

// def.js ->
var bar = function(){
// do something
    this.zxc = function(){
        // do something
    }
}
module.exports.bar = bar;

The main difference is you are now exporting the bar() {...} constructor which can then be used off of the abc required in module?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.