0

Why the console.log shows the name "Alex"? Why doesn't concatenate with the "David" name?

var Obj = function() {
    this.name = "Alex";
    var that = {};
    that.name = "David";
    var name = this.name + " && " + that.name;
    return name;
}

var o = new Obj();
console.log(o.name);
Max
  • 6,821
  • 3
  • 43
  • 59
Alexey
  • 79
  • 3

5 Answers5

2

When you invoke Obj as a constructor by using the new operator, always an object is returned. If the defined return value isn't of type Object, it's just ignored. Within Obj the object to be generated is referenced by this, that is, every property assigned to this is going to be a property of each generated object.

When you invoke Obj as a normal function, it just returns the defined return value and this is ignored.

name and that are just local variables with Obj as scope. They're not assigned to this and thus not part of the returned object. Since the return value name is of type String, it's simply ignored (if invoked as a constructor) and instead an object is returned, which contains all properties assigned to this (so .name = "Alex"):

var Obj = function () {
  var name = "David" // local variable
  this.name = "Alex" // name property of each newly generated object
  return name;
}

var o = new Obj(); // invoke function as a constructor
var p = Obj(); // normal function invocation

console.log(o); // {name: "Alex"}
console.log(p); // "David"
1

Use it like below:

var Obj = function() {
    this.name = "Alex";
    var that = {};
    that.name = "David";
    this.objName = this.name + " && " + that.name;
    //return name;
}

var o = new Obj();
console(o.objName);

Or this, if you want to override name

var Obj = function() {
    this.name = "Alex";
    var that = {};
    that.name = "David";
    this.name = this.name + " && " + that.name;
    //return name;
}

var o = new Obj();
console(o.name);
Bikee
  • 1,197
  • 8
  • 21
0

When you call o.name it will return this.name of the object and not the declared variable ("name"). You need to update this.name value again

try this one :

var Obj = function() {
    this.name = "Alex";
    var that = {};
    that.name = "David";
    this.name = this.name + " && " + that.name;
}

var o = new Obj();
console.log(o.name);
Elie M
  • 263
  • 1
  • 3
  • 15
0

It's a problem with the new Keyword.

One Solution is to get rid of the var keyword and then replace every name with this.name.

Or more simply get rid of the new keyword. Because it will force your Object to return this.

If you are using the new key word this is what happens:

var Foo = fuction(){
   var obj = Object.create(Foo.prototype);
   
    //your Foo code
   
   return obj;
    
}
Simon Appelt
  • 305
  • 4
  • 12
0

var Obj = function() { this.name = "Alex"; var that = {}; that.name = "David"; this.name = this.name + " && " + that.name; return name; } var o = new Obj(); console.log(o.name);