is there ever a use for primitive variables in javascript?

前端 未结 3 1080
北海茫月
北海茫月 2021-01-21 00:59

a pretty simple question, is there ever a case where using a primitive data-type is preferable in javascript, i am specifically bothered by primitive booleans, consider the foll

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 01:24

    Your example:

    var bool = new Boolean(false);
    if (bool){
        alert(bool);
    }
    

    and you're wanting to know why it alerts false.

    bool is the variable, you assigned it a value when you created it. So, when you say if(bool) JavaScript does some coercion and tests whether bool is falsy, it isn't, so the conditional block executes. Now you're at alert(bool) which will try to call the toString method of your object and display the result. The toString method of the boolean object returns the value of the boolean object as a string so, you get the word "false" alerted.

    Go ahead, try

    var bool = new Boolean(false);
    bool.toString = function () {
        return 'I need a banana';
    }
    if (bool){
        alert(bool);
    }
    

    and you'll get completely different results.

    This brings us to your other question of "why" you'd even use the boolean constructor: you can assign properties to the boolean object, you can not assign properties to true and false. You may want to inherit from the boolean object when building some logic handling library with chainable methods, for instance.

提交回复
热议问题