Home >Web Front-end >JS Tutorial >Adding common methods to classes in JavaScript
First of all, JavaScript does not support function overloading. If there are multiple functions with the same name, it will call the one closest to it, which is the last function. This JS does not support function overloading. things require special attention.
Directly define a function or variable. They belong to global functions or global variables. Essentially, they belong to the window object.
Then for the built-in objects in JS, we can provide them with a common method so that they don’t need to be written specifically.
The code is as follows
[javascript]
//We can add methods to the class var i = new Number(10);
Number.prototype.add=function(a){
using using using using using using using ‐ ‐ to window.alert(i.add(20).add(30));
//We can add methods to the class
var i = new Number(10);
Number.prototype.add=function(a){
return this+a;
}
window.alert(i.add(20).add(30));
In this case, we can add methods to the Number object, and we can use it directly.
Look at another code
[javascript]
Array.prototype.find=function(val){
if(this[i] == Val) {d Window.alert ("The lowering is"+i);
Return;}}} Window.alert ("No");
}
var T = New Array (3); 0] = 3;
t[1] = 5;
t[2] = 6;
t.find(4);
t.find(5);
Array.prototype.find=function(val){
for(var i = 0; i < this.length; i++){
if(this[i] == val){
window.alert("subscript is "+i);
return;
}
}
window.alert("None");
}
var t = new Array(3);
t[0] = 3;
t[1] = 5;
t[2] = 6;
t.find(4);
t.find(5);
This provides a common method for the Array object, and applies the this keyword. Such a prototype can provide methods for things equivalent to classes, Mark it