amb*_*tch 11 javascript node.js
在Node.js的Express模块的代码中,我遇到了这一行,为服务器设置了继承:
Server.prototype.__proto__ = connect.HTTPServer.prototype;
Run Code Online (Sandbox Code Playgroud)
我不知道这是什么一样-在MDC文档(https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited#prototype_and_ 原)好像说我可能只是这样做:
Server.prototype = connect.HTTPServer.prototype;
Run Code Online (Sandbox Code Playgroud)
的确,我做了这个测试:
var parent = function(){}
parent.prototype = {
test: function(){console.log('test')};
}
var child1 = function(){};
child1.prototype = parent.prototype;
var instance1 = new child1();
instance1.test(); // 'test'
var child2 = function(){};
child2.prototype.__proto__ = parent.prototype;
var instance2 = new child2();
instance2.test(); // 'test'
Run Code Online (Sandbox Code Playgroud)
看起来一样吗?所以,是的,我想知道设置object.prototype .__ proto是为了什么.谢谢!
vha*_*lac 10
看看上图这个页面(mckoss.com),显示prototype
,constructor
,__proto__
一个小的层次结构关系.此外,图下方的代码也很好地描述了这种关系.
当你有一个功能Base
,并设置中定义的函数对象的原型,该语句Derived.prototype = new Base;
设置__proto__
(实际上是内部[[prototype]]
)的Derived.prototype
,以Base.prototype
自动,使派生本身就是一个类,您可以从实例化对象.这似乎是一种更符合标准的定义派生类的方法.
从我读到的,__proto__
是一种访问[[prototype]]
对象内部的非标准方式.它似乎得到了很好的支持,但我不确定它是否应该被信任.
在任何情况下,您的示例Server.prototype.__proto__ = connect.HTTPServer.prototype;
似乎以相反的方式进行派生:首先定义一个对象,Server
通过定义构造函数和proto,然后[[prototype]]
手动挂钩内部以将其变换为派生自的类HTTPServer
.
至于你建议的替代方案,Server.prototype = connect.HTTPServer.prototype;
:这是一个坏主意.在这里,您将原型设置为与原型Server
相同的对象HTTPServer
.因此,您对Server
类所做的任何更改都将直接反映在其中HTTPServer
,并且可以从其他派生类中访问HTTPServer
.如果派生的两个类HTTPServer
尝试定义相同的成员,则可以对混沌进行成像.
归档时间: |
|
查看次数: |
5771 次 |
最近记录: |