3

Why does "numMyNumber" not appear in Object.getOwnPropertyNames?

Using FireBug console in Firefox.

"use strict";

// MyFunction
function MyFunction() {
   var numMyNumber = 10;
   return numMyNumber;
}

// ["prototype", "length", "name", "arguments", "caller"]
// Why does numMyNumber not appear?
console.log(Object.getOwnPropertyNames (MyFunction)); 

// 10
console.log(MyFunction());
royhowie
  • 11,075
  • 14
  • 50
  • 67
  • The constructor for MyFunction is the entire function. Try running this. `function MyFunction() { var numMyNumber = 10; return numMyNumber; } s = new MyFunction(); console.log(s.constructor)` – sissonb Jul 02 '13 at 23:25

3 Answers3

7

numMyNumber is a local variable.
It is not a property of the function.

To create a property of the function, you need to create the property on the function, just like any other object:

MyFunction.someProperty = 42;

Note that properties of a function are in no way local to a specific call.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0
// MyFunction
function MyFunction() {
   this.numMyNumber = 10;
return this.numMyNumber 


}
// ["prototype", "length", "name", "arguments", "caller"]
// Why does numMyNumber not appear?
alert(Object.getOwnPropertyNames ( new MyFunction)); 

// 10
alert(MyFunction());

1) you need to use this to make variable as property

2) You need to use new to create a new class instance

ManMohan Vyas
  • 4,004
  • 4
  • 27
  • 40
0

To clarify the other answers; there is a difference between the function declaration, an instance created by the function and a function's prototype. I hope the following code will demonstrate that:

//declararion:
function Person(name){
  this.name=name
}
// sayName is a method of a person instance like jon.sayName
Person.prototype.sayName=function(){
  console.log("Hi, I'm "+Person.formatName(this.name));
};
// static property of Person to format name
Person.formatName=function(name){
  return name.toLowerCase().replace(/\b\w/g,function(){
    return arguments[0].toUpperCase();
  });
};

// now we create an instance of person
var jon = new Person("jon holt");
jon.sayName();//=Hi, I'm Jon Holt
// next line's output:  
//["prototype", "formatName", "length", "name", "arguments", "caller"]
console.log(Object.getOwnPropertyNames(Person));
// name in Person isn't the same as name in jon
console.log(Person.name);//=Person
// next line's output: ["name"], name here would be jon holt
console.log(Object.getOwnPropertyNames(jon));
// next line's output: ["constructor", "sayName"]
console.log(Object.getOwnPropertyNames(Person.prototype));

Here is a link to some ways to use function constructors, prototype and inheritance: Prototypical inheritance - writing up

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160