这是我的代码:
var Person = new Function() // same as function Person(){}
var john = new Person()
现在我有这样的原型(prototype)链:Object -> Function -> Person -> john
现在我正在做类似的事情:
Function.prototype.bar = "boo"
所以我希望 Person.bar
和 john.bar
为 "boo"
Person.bar // boo
john.bar // undefined
所以发生了什么?我深入研究发现 john.__proto__ 是 Person 的原型(prototype),但是 john.__proto__.__proto__ 不是 Function 的原型(prototype),它是原型(prototype)Object
,所以我丢失了一条链(Finction)。这就是为什么john.bar
是未定义
的。那么为什么会发生这种情况呢?我不应该能够从 john
访问 Function
原型(prototype)属性吗?
最佳答案
当你有
var Person = new Function()
你得到一个空函数,它不执行任何操作,也不返回任何内容,例如
function Person() {
}
当您使用 new
创建 Person 实例时,新创建的对象将查看 Person.prototype
,并且由于 Person.prototype
继承自 Object
(而不是 Function
),您将看不到 .bar
属性。
function Person() {
}
const john = new Person();
console.log(
Object.getPrototypeOf(john) === Person.prototype,
Object.getPrototypeOf(Person.prototype) === Object.prototype
);
尝试创建函数实例确实很奇怪,但如果您愿意,我想您可以通过让 Person
返回 Function< 来获得您想要的东西
实例:
Function.prototype.bar = "boo"
function Person() {
return new Function();
};
const john = new Person();
console.log(john.bar);
不过,我强烈建议不要尝试创建这样的 Function 实例。
如果你想要一个(奇数)继承链
Object -> Function -> Person -> john
然后你可以使用Object.create
:
//const Person = Object.create(Function);
// or
const Person = new Function();
const john = Object.create(Person);
Function.prototype.foo = 'foo';
console.log(john.foo);
关于Javascript 原型(prototype)链行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006858/