定义Javascript原型 [英] Defining a Javascript prototype

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

问题描述

以下两个Javascript原型之间的功能差异是什么,选择其中一个是否有任何好处?

What are the functional differences between the following two Javascript prototypes, and are there any benefits for choosing one over the other?

选项1:

Person.prototype.sayName = function(name) {
   alert(name);
}

选项2:

Person.prototype = {
   sayName: function(name) {
      alert(name);
   }
}

假设选项2我是否正确会导致某些隐含绑定到原型的函数被废弃?

Am I correct in assuming that Option 2 results in trashing certain functions that are implicitly bound to the prototype?

推荐答案


Am我更正认为选项2会导致某些隐含绑定到原型的函数被废弃?

Am I correct in assuming that Option 2 results in trashing certain functions that are implicitly bound to the prototype?

是的,确切地说。虽然唯一的隐式绑定属性是构造函数属性,但您很少需要它。

Yes, exactly. Though the only implicitly bound property is the constructor property, which you seldom do need.


功能差异是什么?

What are the functional differences?

选项1只是扩展现有原型。如果已经从原型对象继承了 Person 实例,那么它们也可以使用 sayName 方法。使用选项2,新原型将仅用于覆盖后实例化的对象。

Option 1 is just extending the existing prototype. If there are already Person instances inheriting from the prototype object, they will be able to use the sayName method as well. With option 2, the new prototype will only be used for objects that are instantiated after the overwriting.


选择一个有什么好处另一个?

Are there any benefits for choosing one over the other?

现在这些应该是自我解释的。选项1(扩展)被认为是更清晰的,如果您正在修改外来/未知/原生原型,则必须使用它。尽量避免使用选项2.

These should be self-explaining now. Option 1 (extending) is considered cleaner, and is a must if you're modifying foreign/unknown/native prototypes. Try to avoid option 2.

如果您仍然更喜欢对象文字语法,则应考虑使用 Object.assign 扩展现有原型:

If you still like the object literal syntax better, you should consider using Object.assign to extend the existing prototype:

Object.assign(Person.prototype, {
   sayName: function(name) {
      alert(name);
   }
});

您可能需要 polyfill Object.assign for pre -ES6环境。或者, $ .extend 或< a href =http://underscorejs.org/#extend =nofollow> _.extend 同样适用。当然,您最喜欢的库也带有辅助功能。

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

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