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()