TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

The Ways of Javascript Inheritance

8 点作者 brittonrt大约 12 年前
Hey Hacker News! Lets talk about prototypal inheritance in JS!<p>What's the best way of doing it from a code reusability standpoint?<p>What's the best way of doing it from a time to create instance standpoint?<p>What's the best way of doing it from memory footprint standpoint?<p>Of the ways I've seen and tried, John's method seems the easiest to use: http://ejohn.org/blog/simple-javascript-inheritance/<p>But I hate that it has to loop through every property every time you extend a prototype.<p>Most inheritance patterns I've seen need to have the original prototype cloned or instantiated in order extend a new prototype safely. Is there a way to do it that allows all instances at all levels of the inheritance chain to still share the same common methods in memory where they aren't overridden?<p>Thanks!

2 条评论

ricardobeat大约 12 年前
To cut the story short, there is basically a single way to do "proper" inheritance in javascript, which is Crockford's prototypal inheritance [1]. There are a dozen variations on it, here is one:<p><pre><code> function inherits (child, parent) { extend(child, parent) function Ctor () { this.constructor = child } Ctor.prototype = parent.prototype child.prototype = new Ctor() child.__super__ = parent.prototype return child } function Animal ... Animal.prototype.x = ... function Cat ... inherits(Cat, Animal) </code></pre> See Backbone's implementation [2] for another example. This eventually morphed into the standard `Object.create` method [3], supported in IE9+.<p>[1] <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow">http://javascript.crockford.com/prototypal.html</a><p>[2] <a href="http://backbonejs.org/docs/backbone.html#section-186" rel="nofollow">http://backbonejs.org/docs/backbone.html#section-186</a><p>[3] <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create" rel="nofollow">https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...</a>
keefe大约 12 年前
I like something like jQuery.extend(true, {}, src)