Reputation: 31
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
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
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
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