在JavaScript中使用继承模式 [英] Using inheritance patterns in JavaScript

查看:97
本文介绍了在JavaScript中使用继承模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的经验,JavaScript会这样做:

From my experiance, JavaScript does this:


  • 操纵DOM或其​​他主机对象

  • 添加事件处理程序

  • 执行Ajax

因为我开始深入研究原型继承,我会想知道它在实践中是如何实际使用的。有什么用例?

Since I started digging into prototypal inheritance, I would like to know how it is actually used in practice. What are the use cases?

有人在这里积极使用继承模式吗?为什么?

Is anyone here actively using inheritance patterns? What for?

(我知道我的问题有很多答案 - 我只想听听其中的一些,以便在JavaScript中使用继承的感觉)

(I understand that there are lots of answers to my question - I just would like to hear some of them to get the feel of using inheritance in JavaScript)

推荐答案

我使用jQuery(和之前的JavaScript)的经验是原型继承没有我想象的那么有用。它有用,但它对语言并不重要。

My experience working with jQuery (and JavaScript before it) is that prototypical inheritance isn't as useful as I was expecting. It has uses, but it's not fundamentally important to the language.

在Javascript中,如果你想用方法返回一个对象 foo

In Javascript if you want to return an object with a method foo:

return { 
  foo: function() { 
    alert('You called foo!'); 
  }
};

调用者可以将这些对象视为多态 - 也就是说,他们可以调用 foo 而不用担心它的类型对象。不需要继承。

And callers can treat such objects as polymorphic - that is, they can call foo without worrying about what "type" of object it is. There is no need for inheritance.

在这种背景下,原型只是一种优化。它们允许您创建大量对象,而无需在每个实例中复制大量函数属性。这就是jQuery在内部使用它的原因。 jQuery对象有许多函数,将它们复制到每个实例可能是一个很大的开销。

Against this background, prototypes are merely an optimisation. They allow you to create a large number of objects without having to replicate a big set of function properties in each instance. This is why jQuery uses it internally. A jQuery object has dozens of functions, and it might be a major overhead to copy them into every instance.

但是从jQuery用户的角度来看,原型并不是'特别重要。它可以被重写为不使用它们,它仍然可以工作(但可能会使用更多的内存)。

But from the perspective of a user of jQuery, prototypes aren't particularly important. It could be rewritten to not use them and it would still work (but might use a lot more memory).

这篇关于在JavaScript中使用继承模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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