Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Why set a property both on the function and its prototype?

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

The following code was interesting:

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.

So my question is:

Why did the author add that line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

I've fixed the MDN article, nice catch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...