《mastering-javascripts-this》学习笔记

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();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值