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

他の答えを明確にするために; 関数宣言、関数によって作成されたインスタンス、および関数のプロトタイプには違いがあります。次のコードがそれを示していることを願っています。

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

関数コンストラクター、プロトタイプ、および継承を使用するいくつかの方法へのリンクを次に示します

于 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 に答える