1

I am having troubles with objects properties for a NPM module.

I have this code:

var service = { //In my code this lane is: module.exports = { because is for a npm module so the client will call it using require();
    username: 'test',

    serviceFunction: function(){
        console.log(this.username); //Prints service.username
    },

    serviceObject: {                        
        getUsername: function () {
            console.log(this.username); //THIS IS CAUSING THE FAIL, ITS UNDEFINED
        }                   
    }                       
}       

I can access service.username using this.username if it is located in a serviceFunction.

How can I do it while I am in serviceObject.getUsername?

BenG
  • 14,826
  • 5
  • 45
  • 60
Roge
  • 13
  • 2

4 Answers4

1

I'm not a Javascript expert but it seems like you have a object nested into another object. What you really try is to get a field of the parent, so "this" is definetly not binded to the object, you maybe think.

Take a look at this for good solutions: Javascript objects: get parent

Community
  • 1
  • 1
Enak
  • 546
  • 3
  • 15
1

As @Enak said the this inside getUsername refers to getUsername instance.

If you console.log(this) inside getUsername, you will get { getUsername: [Function] }

Instead of

console.log(this.username);

Use:

 serviceObject: {                        
        getUsername: function () {
            console.log(service.username); //'test'
        }                   
    } 
eko
  • 39,722
  • 10
  • 72
  • 98
0

You can not retrieve information for a child object from within a parent object.

One option is to create an init function in the parent to set the same property in the child:-

var service = { 
  username: 'test',

  serviceFunction: function() {
    console.log(this.username); 
  },

  serviceObject: {
    getUsername: function() {
      console.log(this.username); 
    }
  },
  init: function() {
    this.serviceObject.username = this.username;
  }
}

service.init()
service.serviceObject.getUsername(); // test
BenG
  • 14,826
  • 5
  • 45
  • 60
0

It's undefined because the call-site of your serviceObject.getUsername() is explicitly bind to serviceObject, which does not have username property.

You may also use following syntax: serviceObject.getUsername.call(service) to bind getUsername's this to service.

Remember, functions this binding is defined only by the call-site. Wherever you call getUsername(), serviceObject.getUsername(), serviceObject.getUsername.call(service), you are basically binding to different objects.

markoffden
  • 1,406
  • 1
  • 15
  • 31