Home > Web Front-end > JS Tutorial > JavaScript uses Prototype to implement object-oriented methods_javascript skills

JavaScript uses Prototype to implement object-oriented methods_javascript skills

WBOY
Release: 2016-05-16 16:04:13
Original
1056 people have browsed it

The example in this article describes how JavaScript uses Prototype to implement object-oriented methods. Share it with everyone for your reference. The specific analysis is as follows:

Prototype is an attribute of the Function object, which points to another object. All properties and methods of this object will be inherited by the instance of the constructor.

At the same time, prototype also has a reference constructor pointing to the constructor, thus successfully forming a prototype chain structure of circular references.

We can define those unchanged properties and methods directly on the prototype object to save memory overhead.

function Cat(name, color) {
  this.name = name;
  this.color = color;
}
Cat.prototype.type = 'mammal';
Cat.prototype.eat = function() {
  console.log('eat fish');
};
var cat1 = new Cat('Kitty', 'white');
var cat2 = new Cat('Smokey', 'black');
console.log(cat1.type); // mammal
console.log(cat1.eta === cat2.eta);
// TRUE, same reference
console.log(cat1.constructor === Cat)
// TRUE, from Person.prototype
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template