javascript - TypeError: is null - Stack Overflow

I have a situation where I declare an object var o = null;Then, I pass it into a function, do stuff and

I have a situation where I declare an object var o = null;

Then, I pass it into a function, do stuff and maybe assign an object to it.

Later on, I execute parse(o.page). If o is null, then I get "TypeError: o.page is null", and the program stops there because I'm trying to get the property of a null value.

I know one solution could be to initially assign null to all of o's properties.

Just wondering if there is a more subtle way to handle this error. because I would like to handle parse1(o); and parse2(o.page1) where o can be null.

I have a situation where I declare an object var o = null;

Then, I pass it into a function, do stuff and maybe assign an object to it.

Later on, I execute parse(o.page). If o is null, then I get "TypeError: o.page is null", and the program stops there because I'm trying to get the property of a null value.

I know one solution could be to initially assign null to all of o's properties.

Just wondering if there is a more subtle way to handle this error. because I would like to handle parse1(o); and parse2(o.page1) where o can be null.

Share Improve this question edited Jan 20, 2016 at 0:52 Michał Perłakowski 92.9k30 gold badges163 silver badges187 bronze badges asked Nov 17, 2011 at 17:56 airnetairnet 2,6936 gold badges33 silver badges37 bronze badges 1
  • If you show more of your code, I guess there would be a way to create an elegant solution that avoids the problem altogether. – Tomalak Commented Nov 17, 2011 at 18:11
Add a ment  | 

2 Answers 2

Reset to default 3

You could use the ternary operator to do this:

parse2(o ? o.page1 : null)

There is no way to get o.page to work on its own when o is null.

Other ways exist, for example returning {} instead of null, as calling nonexistent properties yields undefined instead of throwing an error.

Generally speaking, avoiding a situation where invalid calls linger in your code is remendable. Either you check the return value before you use it (like above), or you don't return values that can invalidate subsequent code.

Instead of null, assign an empty object.

var o = {};

You cannot assign a property to o if it is null. That would result in

TypeError: Cannot set property 'propname' of null

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744773004a4592875.html

相关推荐

  • javascript - TypeError: is null - Stack Overflow

    I have a situation where I declare an object var o = null;Then, I pass it into a function, do stuff and

    16小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信