Kar Kar - 4 months ago 16
Javascript Question

Factory Pattern - Javascript code - function not to be enumerated


  1. I am trying to use the Factory pattern to create a Person object in javascript. While doing this I am trying to set the property of a function to non enumerable while creating the object. But that does not seem to take effect , please can you tell me why it is still enumerating the function property.

  2. In the defineProperty call, when I pass only the function name I get a error stating that printPersonDetails is undefined. I have to pass obj.printPersonDetails to make it work.






function createPerson(name, age ,sex){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.sex = sex;
obj.printPersonDetails = function(){
console.log("Name: "+ obj.name + " Age: "+ obj.age);
}
Object.defineProperty(obj,obj.printPersonDetails , {
writeable:false,
enumerable:false,
configurable: false
});

return obj;
}
var person1 = createPerson("salman", 29,"M");
var person2 = createPerson("rahman", 59,"M");
var person3 = createPerson("sarah", 19,"F");

//person1.printPersonDetails();
//console.log(person1)

for(prop in person1){
console.log( prop +"->" + person1[prop])}


Output



C:\dev\javascript>node constructorpattern.js
name->salman
age->29
sex->M
printPersonDetails->function (){
console.log("Name: "+ obj.name + " Age: "+ obj.age);
}

Answer

Wrong:

obj.printPersonDetails = function(){
  console.log("Name: "+ obj.name + " Age: "+ obj.age);
}

Object.defineProperty(obj,obj.printPersonDetails , {                
  writeable:false,
  enumerable:false,
  configurable: false
});

Right:

function printPersonDetails(){
  console.log("Name: "+ this.name + " Age: "+ this.age);
}

Object.defineProperty(obj, 'printPersonDetails' , {                
  writeable:false,
  enumerable:false,
  configurable: false,
  value: printPersonDetails
});

BUT, what I think you really want to do is put the utility function on another object entirely.

JavaScript has built-in support for this.

You could use the prototype for that, so instead of

var obj = new Object();

you could use:

var obj = Object.create({ printPersonDetails });

And then instead of for...in you could use Object.keys to avoid seeing the property.

The other approach is to keep the printPersonalDetails function on another object entirely.

Comments