Javascript-Object.getOwnPropertyNames不显示构造函数属性

Javascript - Object.getOwnPropertyNames Does Not Show Constructor Property

本文关键字:构造函数 属性 显示 getOwnPropertyNames Javascript-Object      更新时间:2023-09-26

为什么"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());

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

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

MyFunction.someProperty = 42;

请注意,函数的属性对于特定调用来说并不是本地的。

// 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) 您需要使用this使变量成为属性

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

澄清其他答案;函数声明、函数创建的实例和函数的原型之间存在差异。我希望以下代码将证明:

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

以下是使用函数构造函数、原型和继承的一些方法的链接:原型继承-编写