what is JavaScript object prototype? let see a see

Prototypal inheritance:
all JavaScript objects inherit properties and methods from the prototype.
Date object inherits from Date.prototype. Array object inherits from Array.prototype. Person object inherits from Person.prototype.
Object.prototype located in the top prototype inheritance chain:
the date objects, arrays and objects Person object are inherited from Object.prototype.

Add properties and methods to an object:
Sometimes you want to add a new property (or method) to all existing objects of a given type.
Sometimes, you want to add a new property (or method) to the object constructor.

Use the prototype property
JavaScript prototype property allows you to add new attributes for the object constructor:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript 对象</h1>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.nationality = "English";

var myFriend = new Person("Bill", "Gates", 62, "blue");
document.getElementById("demo").innerHTML =
"The nationality of my friend is " + myFriend.nationality; 
</script>

</body>
</html>

JavaScript prototype property also allows you to add new methods for the object constructor:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript 对象</h1>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName
};

var myFriend = new Person("Bill", "Gates", 62, "blue");
document.getElementById("demo").innerHTML =
"My friend is " + myFriend.name(); 
</script>

</body>
</html>

Please only modify your own prototype. Never modify the prototype standard JavaScript objects.

Published 74 original articles · won praise 27 · views 9521

Guess you like

Origin blog.csdn.net/qq_42526440/article/details/100849626