An error occurred when the constructor returned its own instance inside.

I javascript A novice, recently encountered a problem that I have been unable to understand, as follows:

var A = function() {
    return new B()
}
var B = function() {
    this.name = "B"
}

var a = A()
console.log(Object.getPrototypeOf(a) == B.prototype) // true


var C = function() {
    return new C()
}
var c = C() // 

the personal confusion is why returning your own instance in one constructor will show a stack overflow, but there is no problem returning instances of other constructors.

in addition, as far as I understand, whether the constructor returns its own instance is somewhat similar to recursion , so it returns an error, but what is returned is that an instance object should not continue to make its own calls, so how to understand it? I can"t figure it out all the time.

I hope there are seniors who can give us some advice. Thank you!


you already know the answer, you might as well try this

let C = function(n) {
  console.log(n);
  return new C(n + 1);
}

let c = new C(0);

I don't think it's strange, but of course you can specify that if the constructor of a class tries to instantiate itself with the new keyword, instantiate it with an empty constructor.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2b5e9-2b208.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2b5e9-2b208.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?