How to get the return of an instantiated function (new + return) - Javascript

7

I have a function where I assign values in this, because it will be instantiated

function Teste(){
  this.valor='Valor no this';
  return "Valor no return";
}

Instantiate it

var t = new Teste();

But now, how do I get the string "Valor no return" ?

console.log(t.valor);
console.log(t.return);//?

Code running here: link

    
asked by anonymous 09.02.2015 / 12:02

2 answers

5

This is not possible. You are using the function as a constructor, so it returns the object being created when it is invoked with new (unless you return another object, but there it does not make much sense using new ).

Since in your own example you are attempting to access the supposed return as the property of t , then why not create another property?

function Teste(){
  this.valor='Valor no this';
  this.ret = "Valor no return";
}

var t = new Teste();
console.log(t.valor);
console.log(t.ret);
    
09.02.2015 / 12:05
2

As @bfavaretto said, this is not possible. What you can do is create a method to return the value and chain with the constructor. For example:

function Teste() {
    this.valor = 'valor no this';

    this.getValor = function() {
        return this.valor;
    }
}

var valor = new Teste().getValor();
    
09.02.2015 / 12:08