A case of how Js uses prototype to implement a custom array

黄舟
Release: 2017-10-20 10:42:09
Original
1486 people have browsed it

Preface

Often in front-end interviews or communicating with other colleagues, when it comes to constructing the method of defining a constructor in JS, it is best to use a prototype: define the method The advantage of going to the prototype of the constructor is that the methods of the instance generated by the constructor all point to the index of a function, which can save memory.

This article mainly introduces to you the relevant content about Js using prototype custom array method, and shares it for your reference and study. I won’t say much below, let’s take a look at the detailed introduction.

Question

How to implement the following code:


[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]
Copy after login

Solution

Use the prototype attribute of array and customize theduplicator()method. The js code is as follows:


    Document   
    
Copy after login

The display effect on the console is as follows:

Notes

When writing this codeArray.prototype.duplicatorBe careful not to add any brackets. This inside the function refers to the object that calls this method, which is array.

The above is the detailed content of A case of how Js uses prototype to implement a custom array. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!