Javascript中this关键字的作用范围详解
day01
函数中直接出现的this,指代global或者window
function doStuff(){
console.log(this)
}
doStuff();
day02-1
对象设置中的this,指代当前的对象
var myObj = {
function doStuff(){
console.log(this)
}
}
myObj.doStuff();
day02-2
var myObj = {
function doStuff(){
console.log(this)
}
}
fn = myObj.doStuff();
fn();
此时,对象中的doStuff函数就变成了普通函数,重新给奥了fn,所以fn又是简单函数,所以此时this指代globle或者window
day03
使用new关键字的时候,相当于把函数变成了构造函数,此时函数作为对象构造函数,此时this指代对象
function Foo(){
this.bar = "baz";
console.log(this);
}
var f = new Foo();
console.log(f.bar);
day04
使用函数的方法call(context, para…)的时候,函数中的this关键字将变为context所传入的对象,因此call的作用为定向的改变函数本身所指的环境范围
function doStuff(b){
console.log(this);
return this.a + b;
}
var myContext = {a: 1};
var result = doStuff.call(myContext, 2);
console.log(result);
day04-2
而apply(context, array)只是与call的传入参数不同,其为数组
function doStuff(b, c){
console.log(this);
return this.a + b + c;
}
var myContext = {a: 1};
var result = doStuff.apply(myContext, [2, 3]);
console.log(result);
day04-3
对象中的方法,使用call调用会如何?如下所示,传递进去空对象,如day02-2又例中,此时myObj.doStuff已经是一个普通函数在外侧,所以调用空对象进入后,环境范围变成了空对象,this指向空对象
var myObj = {
foo: "bar",
doStuff: function(){
console.log(this);
}
};
myObj.doStuff.call({});
又例,
var myObj={
foo: "bar",
doStuff: function(){
console.log(this.foo);
}
};
var boundStuff = myObj.doStuff.bind({
foo: "something else"
});
//re-assignmyObj.doStuffsothatitisnowtheboundfunction
myObj.doStuff=boundStuff;
//continuewiththeboundcallandwhatlooksliketheoriginalmethodcall
boundStuff();
myObj.doStuff();