渡一 this指向
2021/9/17 6:04:44
本文主要是介绍渡一 this指向,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.函数预编译过程this->window
2.全局this->window
3.call/apply改变this指向
4.obj.func();func()里的this指向obj
function test(c){ //var this = Object.create(test.prototype); //__proto__:test.prototype var a=123; function b(){} } AO{ arguments:[1], this:window, c:1, a:undefined, b:function(){} } test(1); //new test();
练习题
1. var obj = { a:function(){ console.log(this.name); }, name:'abc' } obj.a(); //abc 2. var name = "222"; var a={ name:"111", say:function(){ console.log(this.name); } } var fun=a.say; fun(); a.say(); //output:222 111 var b={ name:"333", say:function(fun){ fun(); } } b.say(a.say); //重点:这里执行的是fun();不是this.fun();所以是全局this b.say = a.say; b.say(); //output:222 333
var foo='123'; function print(){ var foo='456'; this.foo="789"; console.log(foo); } print();//456 var foo=123; function print(){ this.foo = 234; console.log(foo);//this.foo->234 } print();//234 new print();//123 1.运行test()和new test()的结果分别是什么? var a = 5; function test(){ a=0; console.log(a); console.log(this.a); var a; console.log(a) } test() //test output:0 5 0 //new test output:0 undefined 0 function print(){ var marty = { name:"marty", printName:function(){console.log(this.name);} } var test1 = {name:"test1"}; var test2 = {name:"test2"}; var test3 = {name:"test3"}; test3.pirntName = marty.printName; var printName2 = marty.printName.bind({name:123}); marty.printName.call(test1);//test1 marty.printName.apply(test2);//test2 marty.printName();//marty printName2(); test3.printName();//test3 } var bar = {a:"002"}; function print(){ bar.a="a"; Object.prototype.b="b"; return function inner(){ console.log(bar.a); console.log(bar.b); } } print()(); //output:a b
这篇关于渡一 this指向的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-22项目:远程温湿度检测系统
- 2024-12-21《鸿蒙HarmonyOS应用开发从入门到精通(第2版)》简介
- 2024-12-21后台管理系统开发教程:新手入门全指南
- 2024-12-21后台开发教程:新手入门及实战指南
- 2024-12-21后台综合解决方案教程:新手入门指南
- 2024-12-21接口模块封装教程:新手必备指南
- 2024-12-21请求动作封装教程:新手必看指南
- 2024-12-21RBAC的权限教程:从入门到实践
- 2024-12-21登录鉴权实战:新手入门教程
- 2024-12-21动态权限实战入门指南