Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当我们更改父对象的原型时,_proto__;指向何处?_Javascript_Oop_Prototype - Fatal编程技术网

Javascript 当我们更改父对象的原型时,_proto__;指向何处?

Javascript 当我们更改父对象的原型时,_proto__;指向何处?,javascript,oop,prototype,Javascript,Oop,Prototype,通常,当我们使用“new”关键字创建一个新对象时,实际上所创建对象的\uuuu proto\uuu属性指向父类的prototype属性。我们可以通过以下方式进行测试: function myfunc(){}; myfunc.prototype.name="myfunction"; var child= new myfunc(); child.__proto__=== myfunc.prototype ---> true 但让我们看看当我更改父函数的原型时会发生什么: myfunc.pr

通常,当我们使用“new”关键字创建一个新对象时,实际上所创建对象的\uuuu proto\uuu属性指向父类的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.\uuuuu proto\uuuuu没有指向myfunc.prototype,那么它在对象链中指向哪里?更重要的是,如果它没有指向myfunc.prototype,那么当您使用
新建
操作符创建对象时,它如何访问myfunc类的“name”属性,将创建一个新的JavaScript对象,其内部
\uuuu proto\uuu
属性将设置为函数的
prototype

此时

console.log(myfunc.prototype);
指的是对象

{ name: 'myfunction' }
所以,当你这么做的时候

var child = new myfunc();
myfunc.prototype = {};
内部

child.__proto__ = myfunc.prototype;
正在发生。现在,这里需要了解的重要一点是,在JavaScript中,当您使用赋值运算符时,左侧名称将仅用于引用右侧表达式的结果。因此,在本例中,
child.\uuuu proto\uuu
只是名称
myfunc.prototype
所引用对象的另一个名称。现在,两个
child.\uuuu proto\uuu===myfunc.prototype
都引用了
{name:'myfunction'}
。这就是为什么
child.\uuuu proto\uuu===myfunc.prototype
返回
true

现在,当你

var child = new myfunc();
myfunc.prototype = {};

您正在使
myfunc.prototype
引用新对象
{}
,但
子对象仍然引用旧对象
{name:'myfunction'}
。这就是为什么
child.\uu proto\uu===myfunc.prototype
返回
false
,而
child.name
仍然表示
myfunction

child
在替换之前仍在引用原始的
prototype
对象。实例不会指向构造函数的
prototype
属性;它们使用自己的
[[Prototype]]
属性(它是的一个getter/setter)引用对象本身。请参见这个问题:Ok。它现在指的是什么?应该有一个对象是孩子所指的。_proto___;现在指向的。@Achrome这个问题我已经读了数百万遍了