本文实例讲述了原生javascript中this几种常见用法。分享给大家供大家参考,具体如下:
this的应用 “是” 代名词
this必须出现在函数里面
//------------------默认绑定 function test (){ console.log(this.a);//1 } var a = 1; test();
this取得是window的对象a;此处默认window
//---------------------隐士绑定? function test (){ console.log(this.a);//2 } var foo = { a:2, f:test } var a = 1; foo.f();
此处this取得是foo对象的a;
//---------------------隐士绑定 多层调用链? function test (){ console.log(this.a);//3 } var foo = { a:3, f:test } var foo2 = { a:4, f:foo } var a = 1; foo2.f.f();
此处this取得是foo对象的a,foo2中只起到调用foo,所以thisl指的还是foo;
//---------------------隐士绑定 (隐士丢失) 多层调用链? function test (){ console.log(this.a);//1 } var foo = { a:2, f:test } var a = 1; var fun = foo.f; fun();
由于是赋值 调用的是fun(),foo.f 是取函数,但是this的对象是fun,是window对象,所以只能取得全局变量a
//1,this所在的函数是事件处理函数,那么this就是事件源; var btns = document.getElementsByTagName("button"); 获取所有button for(var i = 0; i < btns.length;i++){ btns[i].onclick = function(){ this代表当前事件源 console.log(this) } }
// 2、this所在函数是构造函数,那么this就是new的对象,并且会生成__proto__属性。 function func(name,age){ this.name = name; this.age = age; // console.log(this) } let f = new func("z",20);
// 3、this所在函数是类的方法,那么this就是调用方法时的对象 function Fnc(name,age){ this.name = name; this.age = age; } Fnc.prototype.eat = function(){ console.log(this); } let fn = new Fnc("a",12); fn.eat(); let fn2 = new Fnc("b",10); fn2.eat();
// 4、this的转移 转移到window var btns = document.getElementsByTagName("button"); //获取所有button for(let i = 0; i < btns.length;i++){ btns[i].onclick = function(){ console.log(this) // this代表点击事件源 setTimeout(function(){ console.log(this); // this代表window对象 发生了转移 },30) } } /* 以上所说的所在函数,重点看关键字function。不会受箭头函数的影响 JavaScript中的一切的一切都属于window对象。window对象可以省略。 所有的全部变量,函数,类,都属于window对象。 this的转移:发生在闭包里。*/
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]