Why should I instantiate certain classes?

0

* Because the class string should not instantiate it to use a function of its prototype? , example: *

String.prototype.mayus = function(){
  
  return this.toUpperCase();
  
};

var frase = "mayusculas".mayus();
console.info(frase);

Now if I want to use a function of class Number , I must instantiate it

WITHOUT INSTANCE:

Number.prototype.restar = function(d){
  
  return d + (-d);
  
};

var b = restar(5);
console.info(b);

WITH INSTANCE:

Number.prototype.restar = function(d){
  
  return d + (-d);
  
};
var k = new Number();
var b = k.restar(5);
console.info(b);
    
asked by Eduardo Sebastian 08.08.2017 в 23:28
source

2 answers

2

In the case of string not the instances because you already have an instance: "mayusculas"

In the case of Number you do not need to create another instance you can call the function restar directly on 5

Number.prototype.restar = function(d) {
    return d + (-d); // Esta línea no tiene sentido pero quien soy yo para juzgar...
};

var b = (5).restar(5);
console.info(b);

Keep in mind that the first 5 is not taken into account by the function subtract, only the parameter (second 5) so the following deveulve the same result:

Number.prototype.restar = function(d) {
    return d + (-d); // Esta línea no tiene sentido pero quien soy yo para juzgar...
};

var b = (100).restar(5);
console.info(b);
    
answered by 08.08.2017 / 23:39
source
0

you still have to add the example similar to the string; the only difference with respect to the chain is the this.valueOf

Number.prototype.duplicar = function(){
   return this.valueOf() + this.valueOf()
  
};
Number.prototype.restar = function(d){
   return this.valueOf() -d;
  
};
var numero =4;
console.info(numero.duplicar());


var numero2 = new Number(10);
console.info(numero2.duplicar());
console.info((100).duplicar());


console.log("resta primer valor:" + numero.restar(5))
console.log("resta segundo valor:" + numero2.restar(5))
console.info("resta sin usar variable" + (100).restar(3));

In the example that you have you are waiting for a parameter called d

Number.prototype.restar = function(d)
    
answered by 08.08.2017 в 23:36