JavaScript:.extend和.prototype用于什么? [英] JavaScript: What are .extend and .prototype used for?

查看:152
本文介绍了JavaScript:.extend和.prototype用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript相对较新,并且继续在我使用的第三方库中看到.extend和.prototype。我认为它与Prototype javascript库有关,但我开始认为情况并非如此。这些用途是什么?

I am relatively new to JavaScript and keep seeing .extend and .prototype in third party libraries I am using. I thought it had to do with the Prototype javascript library, but I am beginning to think that is not the case. What are these used for?

推荐答案

Javascript的继承是基于原型的,所以你扩展了Date,Math等对象的原型。甚至你自己的自定义。

Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.

Date.prototype.lol = function() {
 alert('hi');
};

( new Date ).lol() // alert message

In上面的代码片段,我为所有 Date对象(已经存在的对象和所有新对象)定义了一个方法。

In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).

extend 通常是一个高级函数,它复制你想要从中扩展的新子类的原型基类。

extend is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.

所以你可以这样做:

extend( Fighter, Human )

战斗机构造函数/对象将继承 Human 的原型,因此如果您定义 live > 人类然后战斗机也将继承这些。

And the Fighter constructor/object will inherit the prototype of Human, so if you define methods such as live and die on Human then Fighter will also inherit those.

更新澄清:

高级函数意味着.extend不是内置的,但通常由jQuery等库提供或原型。

"high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.

这篇关于JavaScript:.extend和.prototype用于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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