当我们更改父对象的原型时,__ proto__指向何处? [英] Where the __proto__ is pointing when we change the prototype of the parent object?

查看:164
本文介绍了当我们更改父对象的原型时,__ proto__指向何处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我们使用"new"关键字创建新对象时,实际上所创建对象的 __ proto __ 属性指向父类的 prototype 属性.我们可以如下测试:

Normally when we create a new object using "new" keyword, actually the __proto__ property of the created object is pointing to the prototype property of the parent class. We can test this as below :

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

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

But let's see what happens when I change the prototype of the parent function:

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

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

So if child.__proto__ isn't pointing to the myfunc.prototype, so where it is pointing in objects chain? More important if it doesn't point to the myfunc.prototype, then how it has access to the "name" property of myfunc class?

推荐答案

使用new运算符创建对象时,将创建一个新的JavaScript对象,并将其内部__proto__属性设置为<函数的c2>.

When you are using new operator to create an Object, a new JavaScript Object will be created and its internal __proto__ property will be set to the prototype of the function.

此时

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的原因.

is happening. Now, the important thing to understand here is, in JavaScript, when you use assignment operator, the left hand side name will be just made to refer the result of the right hand side expression. So, in this case, child.__proto__ is just another name for the object referred by the name myfunc.prototype. Now, both child.__proto__ === myfunc.prototype and are referring to { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype is returning true.

现在,当您这样做

myfunc.prototype = {};

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

you are making myfunc.prototype refer the new object {}, but the child.__proto__ is still referring to the old object { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype returns false and child.name still says myfunction.

这篇关于当我们更改父对象的原型时,__ proto__指向何处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆