Home > Web Front-end > JS Tutorial > A case of how Js uses prototype to implement a custom array

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

黄舟
Release: 2017-10-20 10:42:09
Original
1637 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 the duplicator() method. The js code is as follows:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <style></style>
 <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
 <script>
 Array.prototype.duplicator = function() {
 let s = this.concat(this)
 return s
 }
 let t = [1,2,3,4,5].duplicator()
 console.log(t)
</script>

</body>
</html>
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template