function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 创建函数并给函数预设的打头参数
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
this的用法
随着this的使用场合,this的值会发生变化。 总共有四种方式:
纯粹的函数调用
函数体内调用this,代表全局对象Global。
var x = 1;
function test(){
this.x = 0;
}
test();
alert(x); //0
作为对象的方法调用
函数还可以作为某个对象的方法调用,这时this就指这个上级对象。
var obj={
x:10,
fn:function () {
console.log(this.x);
}
}
obj.fn();//10
作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。
var x=10;
function test() {
console.log(this.x);//undefined
this.x=5;
console.log(this.x);//5
}
var o=new test();
console.log(x);//10
console.log(o.x);//5
apply调用
apply()是函数对象的一个方法,用来改变函数的调用对象。this指的就是这个参数。
var x = 0;
function test(){
alert(this.x);
}
var o={};
o.x = 1;
o.m = test;
o.m.apply(); //0,函数调用时的变量环境是定义时的环境
o.m.apply(o); //1,this代表对象o