js面试整理


1.判断基本数据类型typeof  判断对象的类型 Object.prototype.toString.call() 

          //使用 typeof bar === "object" 判断 bar 是不是一个对象弊端?
          //使用 typeof 的判断Object弊端是显而易见的(这种弊端同使用 instanceof):
          let obj = {};
          let arr = [];
          console.log(typeof obj === 'object'); //true
          console.log(typeof arr === 'object'); //true
          console.log(typeof null === 'object'); //true
          //从上面的输出结果可知,typeof bar === "object" 并不能准确判断 bar 就是一个 Object。可以通过 Object.prototype.toString.call(bar) === "[object Object]" 来避免这种弊端:

          let obj = {};
          let arr = [];

          console.log(Object.prototype.toString.call(obj)); //[object Object]
          console.log(Object.prototype.toString.call(arr)); //[object Array]
          console.log(Object.prototype.toString.call(null)); //[object Null]

2.即时执行函数  IIFE 

     (function(){
          var a = b = 3;
      })();

 
      console.log(b); //3 全局变量
      console.log(a); //undefined

      for(var i = 0; i < 5; i++) {
          setTimeout(function() {
              console.log(i);
          }, 1000);
      }
      //上面的输出并不是你以为的0,1,2,3,4,而输出的全部是5,这时 IIFE 就能有用了:

      for(var i = 0; i < 5; i++) {
          (function(i) {
              setTimeout(function() {
                  console.log(i);
              }, 1000);
          })(i)
      }
3 .对于 return 、break、continue 等语句,如果后面紧跟换行,后面一定要加分号;

      function foo1()
      {
          return {
              bar: "hello"
          };
      }

      function foo2()
      {
          return
          {
              bar: "hello"
          };
      }
      console.log(foo1());
      console.log(foo2());//undefined

4.闭包能够访问外部作用域的变量和参数

     (function(x) {
          return (function(y) {
              console.log(x);
          })(2)
      })(1); //1


5.对象调用

      var hero = {
          _name: 'John Doe',
          getSecretIdentity: function (){
              return this._name;
          }
      };

      var stoleSecretIdentity = hero.getSecretIdentity;

      console.log(stoleSecretIdentity);
      console.log(hero.getSecretIdentity());
//      将 getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数:
//      var stoleSecretIdentity = function (){
//          return this._name;
//      }
//      stoleSecretIdentity
//      的上下文是全局环境,所以第一个输出 undefined。若要输出 John Doe,则要通过 call 、apply 和 bind 等方式改变 stoleSecretIdentity 的this 指向(hero)。
//      第二个是调用对象的方法,输出 John Doe。





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值