情况一:

<script>
function test(obj) {
console.log(obj.value)
} function student() {
this.value = "foo";
}
var obj = new student(); test(obj);
</script>

结果:正常输出

情况二:假如obj为null或者undefined呢?

<script>
function test(obj) {
console.log(obj.value)
} function student() {
this.value = "foo";
}
var obj = null;
test(obj);
</script>

结果:报错

总结:只要加入以下这段代码就可以判断出对象是否为null或者undefined,避免报错。

obj = obj || {};

即使是null,也不会报错:

一开始我看代码也没明白是有什么作用,实践之后才明白,加入上面这行代码之后,即使是null都不会报错,只是为undefined。

最新文章

  1. VS2012 还原默认设置
  2. 神盾解密工具 之 解密 “ PHP 神盾解密工具 ”
  3. MySQL命令实例
  4. switch 的一些事
  5. 第26章 创建型模式大PK
  6. LeetCode(76) Minimum Window Substring
  7. java中String类型转换方法
  8. [Android]Fragment源代码分析(二) 状态
  9. 题目:[NOIP1999]拦截导弹(最长非递增子序列DP) O(n^2)和O(n*log(n))的两种做法
  10. Homestead PHP7安装phpredis扩展
  11. # ? &amp; 号在url中的的作用
  12. js返回顶部封装 简洁
  13. 专业辟谣----ThinkSNS不仅仅是微博程序!
  14. 在Ubuntu虚拟机搭建数据库系统
  15. Java基础--Java---IO流------GUI(布局)、Frame、事件监听机制、窗体事件、Action事件、鼠标事件、对话框Dialog、键盘事件、菜单
  16. VBox修改uuid
  17. django的小操作,查询效率up, 引用art-template模板+djangorestframework
  18. Django基础九之中间件
  19. 读《锋利的jQuery》中first-child时的一个细节
  20. **PHP SimpleXML 使用详细例子

热门文章

  1. 基于grafana+prometheus构建Flink监控
  2. 【Leetcode_easy】893. Groups of Special-Equivalent Strings
  3. Docker 安装运行MySQL
  4. 欧姆龙PLC_CP1H_CRC校验
  5. 用pytorch1.0搭建简单的神经网络:进行多分类分析
  6. [SQL] - Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 问题之解决
  7. C++打印水仙花数
  8. 理解atoi()函数
  9. git彻底删除或变更子模块
  10. echarts饼状图位置设置