nodejs object declaration and immediate shorthand if statement crashes the app

我怕爱的太早我们不能终老 提交于 2019-12-11 20:44:16

问题


Can anyone give a comprehensive reason as to why the following node.js script would be crashing?

var _ = require("underscore");

var foo = {
  bar: 123
}

(!_.isNull(foo.bar)?foo.bar = true:"");

The error it produces is:

TypeError: Cannot read property 'bar' of undefined
    at Object.<anonymous> (/Users/blahsocks/test_ob.js:7:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

I can fix the issue by adding a console.log(foo) before the "if" or if I change the if to (typeof ob.bar !== "null") but I wondered if there was a reason this would be causing an error.


回答1:


Automatic semicolon insertion has hit you.

Your code is interpreted as

var foo = {
  bar: 123
}(   !_.isNull(foo.bar)?foo.bar = true:""  );

which is a function call in an assignment. Even before you would get an error that {bar:123} is not a function, you are getting an exception because you are accessing a property on foo before it is assigned a value to (and is still undefined).

To fix this, use

var foo = {
  bar: 123
};

!_.isNull(foo.bar)?foo.bar = true:"";

(where both the semicolon and omitting the parenthesis would have fixed the issue alone).




回答2:


Problem is here:

(!_.isNull(foo.bar)?foo.bar = true:"");

That statement makes no sense, and I don't think you can assign a property inside the inline if statement. I also don't know why you're trying to overwrite 123 with true.

Be that as it may, what you seem to be trying to do should be accomplishable by this:

foo.bar = (!_.isNull(foo.bar) ? true : "");


来源:https://stackoverflow.com/questions/27131613/nodejs-object-declaration-and-immediate-shorthand-if-statement-crashes-the-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!