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.
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);
}
for(prop in person1)is creating a global variable, which you should almost always avoid.