为什么要在函数及其原型上设置属性? [英] Why set a property both on the function and its prototype?

查看:190
本文介绍了为什么要在函数及其原型上设置属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解JavaScript的OOP模型,所以我读这篇文章:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

I was trying to understand OOP model of JavaScript, so I was reading this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

以下代码很有意思:

function Person(gender) {
    this.gender = gender;
    alert('Person instantiated');
}

Person.prototype.gender = '';
var person1 = new Person('Male');
var person2 = new Person('Female');
//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male

有趣且不清楚的是这一行:

What was interesting and not clear to me is this line:

Person.prototype.gender = '';

我不明白所以我用该行测试了代码,没有它。

I didn't understand so I tested the code both with that line and without it.

代码在这两种情况下都能正常工作。

The code is working fine in both conditions.

所以我的问题是:

为什么作者添加该行?

推荐答案

您不应该在原型上设置数据。很多时候从古典语言来到JavaScript的人试图模仿经典继承,但是原型链的不对称性(设置总是本地但得到爬上来链)意味着它是不切实际的。有关原型继承的更多信息,请单击此处

You should not set data on the prototype. A lot of times people who come to JavaScript from classical languages attempt it to emulate classical inheritance, but the assymetric nature of the prototype chain (setting is always local but getting climbs up the chain) means that it's impractical. For more information about prototypical inheritance, click here.

原型用于跨实例共享功能。把功能放在那里。要共享数据,请查看此答案

The prototype is for sharing functionality across instances. Put functions there instead. For sharing data, see this answer.

那篇将性别放在原型上的文章是错误的。这就是为什么在ES6中,最小的类在原型上设置函数,而不是数据成员。请参阅本文,了解为何避免原型数据。

That article putting gender on the prototype is mistaken. This is why in ES6, maximally minimal classes set functions on the prototype, but not data members. See this article on why to avoid data on the prototype.

我修复了MDN文章,很好的捕捉。

I've fixed the MDN article, nice catch.

这篇关于为什么要在函数及其原型上设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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