首页 > 解决方案 > If "fn = new Fn()", why changing Fn.prototype after fn instantiation doesn't change fn.__proto__?

问题描述

Take this code for example:

function Fn() {}
Fn.prototype = {
  isIt: true
};

let fn = new Fn();

Fn.prototype = {
  isIt: false
}

console.log(fn.isIt); // true

When we use new keyword to instantiate a new function, one of the things that happen under the hood is that the prototype of the fn gets "LINKED" to the prototype of Fn. so it's not a copy and for example if we try to run a method on fn which sits on Fn.prototype it executes the code via that object. so i'm just a bit confused about this.

标签: javascriptprototype

解决方案


当执行代码 new Foo(...) 时,会发生以下情况:

  1. 创建了一个新对象,继承自Foo.prototype
  2. 使用指定的参数调用构造函数 Foo,并将 this 绑定到新创建的对象。new Foo 等价于 new Foo(),即如果没有指定参数列表,则调用 Foo 时不带参数。
  3. 构造函数返回的对象(不是 null、false、3.1415 或其他原始类型)成为整个 new 表达式的结果。如果构造函数没有显式返回对象,则使用在步骤 1 中创建的对象。(通常构造函数不返回值,但如果他们想要覆盖正常的对象创建过程,他们可以选择这样做。) - MDN

您会看到此处创建的对象是从Foo.prototype继承的,因此如果您稍后更改它,它对继承的对象没有影响。


推荐阅读