Javascript中的无限原型继承 [英] Infinite prototypal inheritance in Javascript

查看:119
本文介绍了Javascript中的无限原型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Javascript中的原型继承,并且据我所知,我正在尝试使用它将进程发送到无限递归链接。

I'm learning prototypal inheritance in Javascript, and for my understanding I'm trying to use it to send the process into infinite recursive chaining.

我对原型继承的想法是一个对象(它是一个函数)保存原型链接。该对象的任何实例都指向它。因此,如果我说instance.someproperty它会查看父对象的原型链。

My idea of prototypal inheritance is that an object (which is a function) holds prototype link. Any instance of that object points to it. So if I say instance.someproperty it looks into the prototype chain of the parent object.

假设这样,如果我只是将函数原型列表指向自身,它应该进入当对象试图访问某些属性时无限循环。

Assuming this, If I just point function prototype list to itself, it should go into infinite loop when object tries to access some property.

 var p = function(){};

 p.prototype = p;
 // I also tried p.prototype = new p();

 var q = new p();

 // and now when I say q.something, it should never be able to find it.

我想知道为什么这不起作用我怎么能让它进入无限循环。

I want to know why this doesn't work and how can I make it to go into infinite loop.

推荐答案

使用更常见的风格:

function P(){};
P.prototype = P;

在ECMA-262中,内部原型属性 [[Prototype]] 表示。

In ECMA-262, the internal prototype property is denoted by [[Prototype]].

P.prototype 分配不同的对象不会修改 P [[Prototype]] ,所以它的继承链保持为:

Assigning a different object to P.prototype does not modify P's [[Prototype]], so its inheritance chain remains as:

P : P[[Prototype]] -> Function.prototype -> Object.prototype -> null

鉴于 P P.prototype 两者都指向同一个对象, P 实例的 [[prototype]] 链是:

Given that P and P.prototype both point to the same object, the [[prototype]] chain of an instance of P is:

p : p[[Prototype]] -> P : P[[Prototype]] -> Function.prototype -> Object.prototype -> null

所以没有无限循环。

如果没有分配给 P.prototype ,那么 p 的原型链就是:

Without the assignment to P.prototype, p's prototype chain would have been:

p : p[[Prototype]] -> P.prototype -> Object.prototype -> null

要获得无限循环,可以将对象分配给自己的 __proto __ 属性(访问 [[Prototype]] 的公共方式)在那些支持它的浏览器中,但我不确定这是一个好的想法,Firefox抛出:

To get an endless loop, you can assign an object to its own __proto__ property (the public way to access [[Prototype]]) in those browsers that support it, but I'm not sure that's a good idea, Firefox throws:

"TypeError: cyclic __proto__ value".

这篇关于Javascript中的无限原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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