面试总结篇之Javascript(三)

继续Javascript面试总结~
1. bind 函数的作用:
   bind 函数的用法为: function.bind({arguments}) bind 函数的两个作用是: 1. 绑定 this 2. 科里化。
a. 绑定 this:
   bind 方法:改变函数运行时的 this 指向,如 bind(getX) this 绑定到参数 getX
function foo(){
   this.b=100;
   return this.a;
}
    var func=foo.bind({a:1});
    func(); //1 通过bind让this指向a;
    new func();// {b:100} 
注:使用 new 方法时会有特殊情况,如果外部使用 new 来构造函数时,函数没有 return 或者 return 类型为基本类型时返回 this ,且 this 被初始化为一个原型为该对象的空对象,如果函数 return 为对象,则将对象返回给 new
b. currying (科里化)
   把参数拆分开来,例如add.bind(undefined,100)不改变 this 的指向,函数的第一个参数改为 100 ,若函数有三个参数,则只需传入后两个参数即可,有叠加效果。
 
2. 函数属性 arguments
  arguments 得到函数实参个数,类数组对象,原型并不是 array.prototype arguments 与实参有绑定关系,如果未传入实参,则失去绑定关系。严格模式下 arguments 得到的是实参的副本,实际上改变不了实参的值,严格模式下 arguments.callee 不能使用。
 
3. Javascript 中的 this
a. 全局的 this (指象 window
this.document===document;//true
this===window;//true
this.a=37;
b. 一般函数的 this
function f1(){
return this;
}
f1()===window; 
c. 作为对象方法的函数的 this;
var o={  
      prop:37;
      f:function(){
      return this.prop;
     }
}
      console.log(o.f()); //37
d. 对象原型链上的 this
  var o={f:function(){return this.a+this.b;}};
  var p=Object.create(o);
  p.a=1;
  p.b=4;
  console.log(p.f());//5
e.get/set 方法与 this get/set 方法中的 this 一般指向 get/set 方法所在的对象
f. 构造器中的 this
function MyClass(){
     this.a=37;
     }
var o=new MyClass();
console.log(o.a);//37, this 指向MyClass.prototype类型的一个空对象。
g.call/apply 方法与 this 
add.call(o,5,7)// 扁平化传参
add.apply(o,[10,20])// 将参数作为一个数组传进去
h.bind 方法与 this
var g=f.bind({a:"test"});
console.log(g());//test



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值