复制原型继承? [英] Copy prototype for inheritance?

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

问题描述

我正在玩JavaScript,特别是使用类和诸如此类的模拟面向对象编程。

I was playing around with JavaScript in particular simulating object oriented programming with classes and whatnot.

我知道这种实现继承的方式

I knew about this way of achieving inheritance

MyClass.prototype = new AnotherClass();

但我不满意,我不喜欢我需要如何调用<的构造函数code> AnotherClass 。所以我一直在玩,我想出了一些似乎有用的东西,基本上想要第二个意见。

But I wasn't satisfied, I didn't like how I needed to call the constructor of AnotherClass. So I was playing around and I came up with something that seemed to work and basically want a second opinion.

function clone (obj)
{
    function CloneFactory () {}
    CloneFactory.prototype = obj;

    return new CloneFactory();
}

MyClass.prototype = clone(AnotherClass.prototype);

通过克隆原型我们得到它的新副本并将其分配给 MyClass 的原型,以便更改继承的属性不会影响父级的原型属性。像这样会 MyClass.prototype = AnotherClass.prototype

By cloning the prototype we get a new copy of it and assign that to MyClass's prototype so that changing the inherited properties will not affect the parent's prototype's properties. Like this would MyClass.prototype = AnotherClass.prototype.

我运行压力测试,这在某些情况下效率更高环境,即父代的构造函数中有很多代码,否则大致相同。另一个好处(或者至少我发现它是有益的)是它允许在某种程度上隐藏子类的信息。任何特权方法和成员都不会被继承。

I ran stress tests and this is more efficient under certain circumstances, i.e. when there's a lot of code in the parent's constructor, otherwise it's about the same. Another benefit (or at least I find it to be beneficial) is that it allows to some extent information hiding from the subclasses. Any privileged methods and members will NOT be inherited.

我忽视了一些重大缺陷吗?

Is there some major pitfall that I'm overlooking?

我不是JavaScript的专家,实际上我对JavaScript很新,所以我想对此有第二意见,因为我似乎无法通过Google找到任何东西。我不想实现错误的代码:)!

I'm not an expert with JavaScript, actually I'm fairly new to JavaScript, so I'd like to have a second opinion on this because I can't seem to find anything through Google. I don't want to implement bad code :)!

推荐答案

几乎正是 Object.create 可以。您编写的函数是该方法的一个非常标准的polyfill。

This is almost exactly what Object.create does. The function you've written is a pretty standard "polyfill" for that method.

这是一种以更接近的方式抽象对象创建的一种非常常见的方式真正的原型继承。绝对是一种安全的做事方式。

This is a really common way of abstracting object creation in a way that more closely reflects "true" prototypal inheritance. Definitely a safe way to do things.

哦,这里有一个指向的对象的链接 ,如果您有兴趣: https://developer.mozilla.org / en / JavaScript / Reference / Global_Objects / Object / create /

Oh, and here's a link to the MDN entry for Object.create, if you're interested: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create/

你会在底部注意到它们实际上包含了polyfill,这几乎是与您的代码相同,除了一些安全检查和变量名称。

You'll notice at the bottom that they actually include the polyfill, which is pretty much identical to your code, save for some safety checks and variable names.

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

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