【问题标题】:Where the __proto__ is pointing when we change the prototype of the parent object?当我们改变父对象的原型时 __proto__ 指向哪里?
【发布时间】:2015-08-20 22:30:20
【问题描述】:

通常当我们使用“new”关键字创建一个新对象时,实际上创建的对象的__proto__属性指向父类的prototype属性。我们可以如下测试:

function myfunc(){};
myfunc.prototype.name="myfunction";
var child= new myfunc();
child.__proto__=== myfunc.prototype  ---> true

但是让我们看看当我改变父函数的原型时会发生什么:

myfunc.prototype={};
child.__proto__=== myfunc.prototype  ---> false
child.name   ------> "myfunction"

如果 child.__proto__ 没有指向 myfunc.prototype,那么它在对象链中指向哪里?更重要的是,如果它不指向 myfunc.prototype,那么它如何访问 myfunc 类的 "name" 属性?

【问题讨论】:

  • child 在被替换之前仍在引用原始的 prototype 对象。实例不指向其构造函数的prototype 属性;他们使用自己的 [[Prototype]] 属性(__proto__ 是其获取器/设置器)引用对象本身。
  • 好的。它现在指向哪里?现在应该有一个 child.__proto__ 指向的对象。
  • @Achrome 我已经读过这个问题数百万次了

标签: javascript oop prototype


【解决方案1】:

当您使用new 运算符创建对象时,将创建一个新的JavaScript 对象,其内部__proto__ 属性将设置为函数的prototype

此时

console.log(myfunc.prototype);

指的是对象

{ name: 'myfunction' }

所以,当你这样做时

var child = new myfunc();

内部

child.__proto__ = myfunc.prototype;

正在发生。现在,这里要理解的重要一点是,在 JavaScript 中,当您使用赋值运算符时,左侧名称将仅用于引用右侧表达式的结果。因此,在这种情况下,child.__proto__ 只是名称 myfunc.prototype 所引用的对象的另一个名称。现在,child.__proto__ === myfunc.prototype{ name: 'myfunction' } 均指代。这就是child.__proto__ === myfunc.prototype 返回true 的原因。

现在,当你这样做时

myfunc.prototype = {};

您正在使myfunc.prototype 引用新对象{},但child.__proto__ 仍然引用旧对象{ name: 'myfunction' }。这就是为什么child.__proto__ === myfunc.prototype 返回falsechild.name 仍然是myfunction

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2016-05-22
    • 2013-12-09
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    相关资源
    最近更新 更多