Question :
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
Answer :
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);
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();