What values can a constructor return to avoid returning this?

前端 未结 6 625
傲寒
傲寒 2020-11-22 08:06

What are the exact circumstances for which a return statement in Javascript can return a value other than this when a constructor is invoked using

6条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 08:53

    Trying to put a few points in simpler words.

    In javascript, when you use a new keyword on a function and if,

    1. function does not return anything, it will return an intended object

    function User() {
      this.name = 'Virat'
    }
    
    var user = new User();
    console.log(user.name); //=> 'Virat'

    1. function returns any truthy complex object [object, array, function etc], that complex object takes priority and user variable will hold the returned complex object

    function User() {
      this.name = 'Virat';
      return function(){};
    }
    
    var user = new User();
    console.log(user.name); //=> undefined
    console.log(user); //=> function

    1. function returns any literal, constructor takes priority and it will return an intended object

    function User() {
      this.name = 'Virat';
      return 10;
    }
    
    var user = new User();
    console.log(user.name); //=> 'Virat'

提交回复
热议问题