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]
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>
The display effect on the console is as follows:
Notes
When writing this codeArray.prototype.duplicator
Be 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!