JavaScript中this关键字用法实例分析

本文实例总结了JavaScript中this关键字用法分享给大家供大家参考,具体如下:

例1:

rush:js;"> function a(){ var user = "yao"; console.log(this.user);//undefined console.log(this);//window } a();

等价于:

rush:js;"> function a(){ var user = "yao"; console.log(this.user);//undefined console.log(this);//window } window.a();

this指向的是window。

例2:

rush:js;"> var o = { user:"yao",fn:function () { console.log(this.user);//yao } } o.fn();

this指向的是o。

例3:

rush:js;"> var o = { user:"yao",fn:function () { console.log(this.user);//yao } } window.o.fn();

this指向的是o。

rush:js;"> var o = { a:10,b:{ a:12,fn:function () { console.log(this.a);//12 } } } o.b.fn();

this指向的是b。

例4:

rush:js;"> var o = { a:10,fn:function () { console.log(this.a);//undefined console.log(this);//window } } }; var j = o.b.fn; j();

综上所述:

this的指向永远是最终调用它的对象。

当this遇上函数的return:

例5:

rush:js;"> function fn(){ this.user = "yao"; return {}; } var a = new fn; console.log(a.user);//undefined

例6:

rush:js;"> function fn(){ this.user = "yao"; return function(){}; } var a = new fn; console.log(a.user);//undefined

例7:

rush:js;"> function fn(){ this.user = "yao"; return 1; } var a = new fn; console.log(a.user);//yao

例8:

rush:js;"> function fn(){ this.user = "yao"; return undefined; } var a = new fn; console.log(a.user);//yao

this指向的是函数返回的那个对象。

rush:js;"> function fn(){ this.user = "yao"; return null; } var a = new fn; console.log(a.user);//yao

虽然:null是对象,但是此时this指向的仍然是函数的实例。

PS:

在"use strict"模式下,this认的指向是undefined,而不是window。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《

希望本文所述对大家JavaScript程序设计有所帮助。

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面