gpt4 book ai didi

javascript - Object.getOwnPropertyNames 中的混淆

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:24 24 4
gpt4 key购买 nike

你好下面的代码

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

我得到的结果是工作、项目、显示,但是当我以这种方式使用原型(prototype)定义属性时

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 实例,其 prototype 包含指向该函数的“构造函数”属性。为原型(prototype)分配新属性将保留它。因此,使用 new employee 创建的对象将继承此“构造函数”属性,该属性将说明它们是用什么构造的。

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

但是,当您覆盖整个 prototype 时,您也会删除 constructor 属性。对象当然有一个构造函数 (Object),但它是继承的,所以它不会显示为“OwnProperties”。

关于javascript - Object.getOwnPropertyNames 中的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com