Number.prototype.sq = (n) => return Math.sqrt(this);
var b = sq(5);
console.log(b);
The idea of my code is to return the square root of this, but it throws an error, why?
Number.prototype.sq = (n) => return Math.sqrt(this);
var b = sq(5);
console.log(b);
The idea of my code is to return the square root of this, but it throws an error, why?
To work first you have to remove the this
of your lambda function since it is referencing the anonymous function and not the number that you are passing as an argument, instead put the n
that is your argument .
When you create a function with prototype, you are adding functionality to the class (by calling it in some way), then to access that function you have to create an instance of the class, in your case an instance of Number
var b=new Number();
It would stay like this
Number.prototype.sq = (n) => Math.sqrt(n);
var b=new Number();
console.log(b.sq(5) );
If you want to avoid creating an instance, you can create a class function
Number.sq = (n) => Math.sqrt(n); //Sin prototype
var b = Number.sq(5);
console.log(b);
Here you can better understand how prototypes work
I have slightly changed your function so that I do not have any problems.
Previously, you were not assigning the function to any variable that was number.
Number.prototype.sq = function() {
return Math.sqrt(this);
};
var numero = 5;
var b = numero.sq();
console.log(b);
The correct form of what you want with ECMAScript 6 is as follows
class Numero {
constructor(numero) {
this.numero = numero;
}
sq(){
return Math.sqrt(this.numero);
}
}
var miNumero = new Numero(6);
console.log(miNumero.sq());
what you want to do is a hybrid of ECMAScript 5 and ECMAScript 6 the way to do it with ECMAScript 5 is as follows
var Numeros = function (numero) {
this.numero = numero;
};
Numeros.prototype.sq = function () {
return Math.sqrt(this.numero);
};
let miNum = new Numeros(5);
console.log(miNum.sq());
You can see more documentation at link