javascript – Object.getOwnPropertyNames中的混淆

您好,以下代码

   function employee()
    {
    	this.name="john";
    }

    employee.prototype={
    		job:"manager",
    		projects:["sales","training","construction"],
    		display:function()
    		{
    			alert(this.name+" is a "+ this.job);
    		}
    }

    var property=Object.getOwnPropertyNames(employee.prototype);
    alert(property);

我得到结果作为工作,项目,显示,但当我用这种方式使用原型定义属性

function employee()
    {
    	this.name="john";
    }

    employee.prototype.job="manager";
    employee.prototype.projects=["sales","training","construction"];
    employee.prototype.display=function()
    {
    	alert(this.name+"is a"+ this.job);
    }


 var property=Object.getOwnPropertyNames(employee.prototype);
 alert(property);

我得到结果作为构造函数,工作,项目,显示

我的问题是为什么我没有在第一个案例的结果中得到构造函数?

最佳答案 当您声明employee函数时,它会实例化一个Function实例,其原型包含指向该函数的“constructor”属性.为原型分配新属性将保留该属性.因此,使用新员工创建的对象将继承此“构造函数”属性,该属性将说明它们构造的内容.

function C(){}
console.log(C.prototype.constructor) // returns C
console.log(C.prototype.hasOwnProperty("constructor") // true

cosole.log(new C().constructor) // C
cosole.log(new C().hasOwnProperty("constructor") // false, it's inherited

但是,当您覆盖整个原型时,您还要删除构造函数属性.对象有一个构造函数(Object),但是它是继承的,所以它不会显示为“OwnProperties”.

点赞