0

I hava a simple js function

var myFunction=function(){
    var age=20;
    this.name="bar";
    var show=function(){
        console.log(age);
    }
}

and creating an instance like:

 var obj=new myFunction();
 console.log(obj.show())

logs:this

how can I resolve it?? I have tried to search SO for this but could not find my solution. UPDATE I want all private members to remain same.

Hemant
  • 1,961
  • 2
  • 17
  • 27

4 Answers4

3

The problem with your code is that the show method is not accessible outside the function scope of myFunction.

In Javascript, the scope is defined within the function (Ignoring ES6 block scope). So, the scope of variables age, name, show is within the function. However, when you use this and use the constructor function (new) the newly created object contains the property which are associated with the this keyword. In your case, you associate only the name property with the new object and did not associate the show function with this.

One of the solution is using the Module Pattern. You can make the public accessible property by returning an Object which encapsulates the publicly exposed properties. So, in your case, you can expose name and show methods from the myFunction. Also, no need to do console.log twice. You can get the output by obj.show(). Otherwise it will log undefined as show function doesn't return anything.

var myFunction=function(){
    var age=20;
    var name="bar";
    var show=function(){
        console.log(age);
    }
    
    return {
      name : name,
      show : show,
    }
}

 var obj=new myFunction();
 obj.show()
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
0

Try changing your code to

var myFunction=function(){
var age=20;
this.name="bar";
this.show=function(){
console.log(age);
}
}

Changing your show var to be a property

taquion
  • 2,667
  • 2
  • 18
  • 29
0

A clean solution would be to make the function publicly accessible as an object property:

var myFunction = function() {
  var age = 20;
  this.name = "bar";
  
  this.show = function() {
    console.log(age);
  }
}

var obj = new myFunction();
obj.show();
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

With var you declared show as a variable and not a member of myFunction. The same with age, if it is a class member, you should also use this

This one way to change it:

var myFunction = function() {
    this.age = 20;
    this.name="bar";
    this.show = function() {
        console.log(age);
    }
}

var obj = new myFunction();
console.log(obj.name);
obj.show();
Find further information here: best approach to member variables in object-oriented javascript?
Community
  • 1
  • 1
ppasler
  • 3,579
  • 5
  • 31
  • 51