user2544546
user2544546

Reputation: 31

Javascript - Object.getOwnPropertyNames Does Not Show Constructor Property

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

Upvotes: 3

Views: 670

Answers (3)

HMR
HMR

Reputation: 39290

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

Upvotes: 0

ManMohan Vyas
ManMohan Vyas

Reputation: 4062

// 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

Upvotes: 0

SLaks
SLaks

Reputation: 887767

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.

Upvotes: 7

Related Questions