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

查看:31
本文介绍了定义 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?

推荐答案

我是否正确地假设选项 2 会导致某些隐式绑定到原型的函数被破坏?

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

是的,没错.虽然唯一的隐式绑定属性是 constructor 属性,但您很少需要.

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

有哪些功能差异?

选项 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(扩展)被认为更简洁,如果您要修改外部/未知/本地原型,则必须使用选项 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 用于 ES6 之前的环境.或者,$.extend_.extend 也能正常工作.当然,您最喜欢的库也为此提供了一个辅助函数.

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

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