文章首发:http://www.cnblogs.com/sprying/p/3573456.html

使用this的几种场合

1. 执行函数时,判断函数是对象方法还是一个单独的函数?单独的函数this===window;
对象方法,this == 对象。

function UseThis(){
console.log(this === window);
this.instancePro = 1;
}
UseThis.objPro = 2;
UseThis.objMethod = function(){
console.log(this.objPro);
}
UseThis();//true 不管嵌套多深,执行函数时,函数内的this === window
console.log(instancePro);// var useThis = new UseThis();//false 当前是A是个构造函数,构造函数内的this,是new创建的实例
console.log(useThis.instancePro);// UseThis.objMethod();//2 当前函数是对象方法,this===UseThis
var fn = UseThis.objMethod;
fn();//undefined

打开测试页面,启动调试器

2. 函数由bind方法返回后,this指向bind的第一个参数。

3. 通过call(apply)执行函数,this指向call(apply)的第一个参数。

/*函数两次调用call*/
function doubleBind() {
  console.log(this.doubleVariable);
}
(function () {
  console.log(this.doubleCalendar);//
  doubleBind.call({doubleVariable: 1});//
}).call({doubleVariable: 2});

4. 一个函数,先调用bind,再使用call执行时,this指向bind的第一个参数。

/*由函数Bind绑定返回函数再调用call*/
function funBind() {
console.log(this.pro);
}
var relFun = funBind.bind({pro: 2});
relFun.call({pro: 3});//

出道题

var con_inObj = {
variable :"sprying",
cons_fun:function(){
console.log(this.variable);
}
}
var new_obj = new con_inObj.cons_fun();//? <!-- from 前端乱炖 -->
var x = 5;
var example = {
x: 100,
a: function () {
var x = 200;
console.log('a context: %s, var x = %s', this.x, x);
},
b: function () {
var x = 300;
return function () {
var x = 400;
console.log('b context: %s, var x = %s', this.x, x);
};
},
c: function () {
var other = {
x: 500
};
var execB = this.b().bind(other);
execB();
return execB;
}
}
console.log('example.x:' + example.x);
example.a();
example.b()();
example.a.call({
x: 9999
}); var execB = example.c();
execB.call({
x: 9999
});

想知道结果的同学,点击链接,打开调试器

最新文章

  1. Git Windows客户端保存用户名与密码
  2. JS自执行匿名函数
  3. Round in Oracle/VBA
  4. [ubuntu] Can not run OpenProj on Ubuntu
  5. z-index总结【转载http://www.cnblogs.com/mind/archive/2012/04/01/2198995.html】
  6. 分页写入文件,第二次分页前一定要关闭IO流啊。。否则文件写不全。。- -粗心
  7. Codeforces Gym 100531J Joy of Flight 变换坐标系
  8. webpack资料
  9. Gizmos绘制塔防游戏网格
  10. 10招搞定web设计风格指南
  11. Webx小应用的实现整理与分析
  12. 3道acm简单题(2011):1.判断是否能组成三角形;2.判断打鱼还是晒网;3.判断丑数。
  13. ArrayList和Vector区别
  14. System.DllNotFoundException: Unable to load DLL &#39;libgdiplus&#39;: The specified module could not be found.
  15. mysql操作数据表中的记录1
  16. Marriage Match II HDU - 3081(二分权值建边)
  17. React Router API文档
  18. Arduino IDE for ESP8266 ()组网
  19. materia官网地址
  20. 如何在SpringMVC中使用REST风格的url

热门文章

  1. HBase优化实战
  2. C语言字符串拼接
  3. day3学python 字典+列表集合+文件读取
  4. 美团Java实习面试经历(拿到Offer)
  5. php 面试常问问题
  6. AttributeError: module &#39;yagmail&#39; has no attribute &#39;SMTP&#39;,关于使用yagmail发邮件报错的解决方法
  7. [国家集训队]部落战争 最大流 BZOJ2150
  8. bootstrap Table从零开始
  9. opencv基本操作
  10. Tarjan算法打包总结(求强连通分量、割点和Tarjan-LCA)