记录粗心的问题

来源:互联网 发布:unity3d t4m插件 编辑:程序博客网 时间:2024/06/08 02:10
var o = {    config: true,    logConfig: function() {        console.log('config is: ' + this.config ? 'true' : 'false');    },    toggleConfig: function() {        this.config = !this.config;        console.log(this.config);    }}o.logConfig();o.toggleConfig();o.logConfig();

上面是经过简化的简洁结构,大意的我想当然地认为输出分别是:

"config is: true"false"config is: false"

然而事实并非如此,正确的输出结果是:

"true"false"true"

原因在于优先级,加法运算的优先级大于三元运算符,所以实际情况是,'config is: ' + this.config ? 'true' : 'false' 的运算不是 'config is: ' + (this.config ? 'true' : 'false') 而是 ('config is: ' + this.config) ? 'true' : 'false' ,因此总是输出'true'