What values can a constructor return to avoid returning this?

前端 未结 6 724
傲寒
傲寒 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:31

    As a side note, the return value or this is just part of the equation.

    For example, consider this:

    function Two() { return new Number(2); }
    var two = new Two;
    two + 2; // 4
    two.valueOf = function() { return 3; }
    two + 2; // 5
    two.valueOf = function() { return '2'; }
    two + 2; // '22'
    

    As you can see, .valueOf() is internally used and can be exploited for fun and profit. You can even create side effects, for example:

    function AutoIncrementingNumber(start) {
        var n = new Number, val = start || 0;
        n.valueOf = function() { return val++; };
        return n;
    }
    var auto = new AutoIncrementingNumber(42);
    auto + 1; // 43
    auto + 1; // 44
    auto + 1; // 45
    

    I can imagine this must have some sort of practical application. And it doesn't have to be explicitly a Number either, if you add .valueOf to any object it can behave as a number:

    ({valueOf: function() { return Math.random(); }}) + 1; // 1.6451723610516638
    

    You can exploit this to make an object that always returns a new GUID, for instance.

提交回复
热议问题