Bug in prototype of number Javascript

0

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?

    
asked by Eduardo Sebastian 08.08.2017 в 19:49
source

3 answers

1

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

    
answered by 08.08.2017 / 22:12
source
2

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);
    
answered by 08.08.2017 в 19:53
0

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

    
answered by 08.08.2017 в 22:27