3

为什么“numMyNumber”不出现在 Object.getOwnPropertyNames 中?

在 Firefox 中使用 FireBug 控制台。

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

3 回答 3

7

numMyNumber是一个局部变量
它不是函数的属性。

要创建函数的属性,您需要在函数上创建属性,就像任何其他对象一样:

MyFunction.someProperty = 42;

请注意,函数的属性绝不是特定调用的本地属性。

于 2013-07-02T23:21:14.463 回答
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

于 2013-07-03T00:31:12.637 回答
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)您需要使用来将变量作为属性

2)您需要使用new来创建一个新的类实例

于 2013-07-02T23:33:40.670 回答