继续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