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

Asked

Viewed 1,022 times

7

I have a Function where I assign values in this, why it will be instantiated

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

I urge her

var t = new Teste();

But now, like me for the string "Valor no return"?

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

Code running here: http://jsbin.com/zariyo/1/edit

  • Because the guy deserved -1?

  • I don’t know, it wasn’t me.

  • The comments should explain why, but anyway...

2 answers

5


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

Since in your own example you are trying to access the supposed return as 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);
  • I knew I couldn’t do it, because I couldn’t do it. But that "Why?" and "Can’t I do it". Obrg

  • Because the constructor needs to return the object it creates. You could even return another object (not a string that is a primitive value), but then lose access to the property valor who has just created.

2

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

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

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

var valor = new Teste().getValor();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.