this指向
function fn(){
console.log(this);
}
fn();
document.onclick = fn;
var obj = {
fn : function(){
console.log(this);
}
}
obj.fn();
改变this指向
- call
- apply
- bind
function fn(){
console.log(this);
}
fn();
fn.call( document );
fn.apply( document );
fn.bind(document);
var x = fn.bind(document);
x();
三种方法的传参方式
function sum (a,b){
console.log(this);
console.log(a + b);
}
sum.call(oWarp,2,5);
sum.apply(oWarp,[2,5]);
var = fn.bind(null,2,5);
x();
bind的柯里化
function fn(a,b,c){
console.log(this);
console.log(a + b + c);
}
var x = fn.bind(null,1,2);
x(3);
例子
var obj = {name: "zhangsan"};
function fn(){
console.log(this);
}
document.onclick = function(){
fn.call(obj);
}
document.onclick = fn.bind(obj);