面试总结篇之Javascript(三)

来源:互联网 发布:mysql 有符号整型 编辑:程序博客网 时间:2024/06/04 10:56
继续Javascript面试总结~
1. bind函数的作用:
   bind函数的用法为:function.bind({arguments})bind函数的两个作用是:1.绑定this2.科里化。
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.prototypearguments与实参有绑定关系,如果未传入实参,则失去绑定关系。严格模式下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方法与thisget/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