《mastering-javascripts-this》学习笔记
2016-02-01 23:53
771 查看
Javascript中this关键字的作用范围详解
day01
函数中直接出现的this,指代global或者windowfunction 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();
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享
- 如何创建对象以及jQuery中创建对象的方式
- 数组方法汇总