Home Web Front-end JS Tutorial Understanding javascript object inheritance_javascript skills

Understanding javascript object inheritance_javascript skills

May 16, 2016 pm 03:05 PM

Let’s start with a deeper study: What is JavaScript object inheritance?

For example, we have a constructor for the "animal" object.

  function animal() {
    this.type = '动物';
  }
Copy after login

There is also a constructor for the "cat" object.

  function cat(name,color) {
    this.name = name;
    this.color = color;
  }
Copy after login

We know that cats are also animals. If this cat object wants to inherit the attributes of the animal object, what should we do?

Constructor Binding
Using constructor binding is the simplest method. Just use call or apply to bind the parent object to the self object.

 function cat(name,color) {
    animal.apply(this,arguments);
    this.name = name;
    this.color = color;
  }
  var cat1 = new cat("haha", 'red');
  console.log(cat1.type); //动物
Copy after login

However, this method is relatively rare.

Copy inheritance
If you copy all the properties and methods of the parent object into the child object, inheritance can also be achieved.

  function extend(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
      c[i] = p[i];
      }
    c.uber = p;   //桥梁作用
  }
Copy after login

How to use:

 extend(cat, animal);
  var cat1 = new cat("haha","red");
  alert(cat1.type);   // 动物
Copy after login

Prototype inheritance (prototype)
Compared with the direct binding above, the prototype inheritance method is more common. Regarding prototype, I briefly summarized it myself.

Each function has a prototype attribute, which is a reference to an object. When using the new keyword to create a new instance, the instance object will inherit the properties and methods from the prototype object.

In other words, if the prototype attribute of the "cat" constructor points to an "animal" instance, then when the "cat" object instance is created, the properties and methods of the "animal" object will be inherited.

Inherited instance

 cat.prototype = new animal();
  cat.prototype.constructor = cat;
  var cat1 = new cat("haha","red");
  console.log(cat1.constructor == cat);  //true
  console.log(cat1.type); // 动物
Copy after login

1. In the first line of the code, we point the prototype object of the cat function to an instance of the animal object (which contains the type attribute of animal).

2. What does the second line of code mean?

1), first, if we did not add this line of code, run

cat.prototype = new animal();
console.log(cat.prototype.constructor == animal); //true
In other words, each prototype object actually has a constructor attribute pointing to its constructor.

2), let’s look at the code below

 cat.prototype = new animal();
  var cat1 = new cat("haha", 'red');
  console.log(cat1.constructor == animal);  //true
Copy after login

From the above we see that the constructor of instance cat1 is animal, so it is obviously wrong. . . cat1 is obviously generated by new cat(), so we should correct it manually. The constructor value of the cat.prototype object is changed to cat.

3), So this is something we should pay attention to. If we replace the prototype object, we should manually correct the constructor attribute of the prototype object.

o.prototype = {};
o.prototype.constructor = o;
Inherit prototype directly
Since in animal objects, immutable attributes can be written directly in animal.prototype. Then directly let cat.prototype point to animal.prototype to achieve inheritance.

Now we first rewrite the animal object as:

  function animal() {
  }
  animal.prototype.type = '动物';
Copy after login

Then implement inheritance:

 cat.prototype = animal.prototype;
  cat.prototype.constructor = cat;
  var cat1 = new cat("haha","red");
  console.log(cat1.type); // 动物
Copy after login

Compared with the previous method, this method is more efficient (no animal instance is created) and saves space. But is this the right thing to do? The answer is incorrect, let's keep looking.

cat.prototype = animal.prototype;
This line of code makes cat.prototype and animal.prototype point to the same object, so if a certain attribute of cat.prototype is changed, it will be reflected in animal.prototype, which is obviously not what we want to see.

For example, if we run:

console.log(animal.prototype.constructor == animal) //false
The result is false, why? cat.prototype.constructor = cat; This line will also change the constructor attribute of animal.prototype.

Use empty objects as intermediaries

  var F = function(){};
  F.prototype = animal.prototype;
  cat.prototype = new F();
  cat.prototype.constructor = cat;
Copy after login

Combining the above two methods, because F is an empty object, it takes up almost no memory. At this time, modifying the prototype object of cat will not affect the prototype object of animal.

console.log(animal.prototype.constructor == animal); // true
Then we encapsulate the above method:

  function extend(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
  }
Copy after login

When using it, the method is as follows:

 extend(cat,animal);
  var cat1 = new cat("haha","red");
  console.log(cat1.type); // 动物
Copy after login

Child.uber = Parent.prototype; This line of code acts as a bridge, allowing the uber attribute of the child object to directly point to the prototype attribute of the parent object. This is equivalent to opening a channel called uber on the self-object, allowing instances of the child object to Ability to use all properties and methods of the parent object.

The above is my understanding of JavaScript object inheritance. I hope it can help you more or less. Thank you for reading.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles