Benjamin W Benjamin W - 2 months ago 12
Javascript Question

pass constructor object into self invoke function

#1 //pass obj into self invoke, works fine
var foo = {
a: 1
};

(function(o){
console.log(o.a);
})(foo);

#2 //this is not working
var foo = function(){
this.a = 1;
};

(function(o){
console.log(o);
})(foo);


I'm new in Javascript, I try to pass an object into self invoke

my problem is when I try to pass constructor obj, its not working

anyone know why?

Answer

In order #2 to work you have to correct it as follows;

var foo = (function(){
  return this.a = 1; 
})();

(function(o){
  console.log(o);
})(foo);