js中程序员的迷茫,this的归属问题

来源:互联网 发布:手机辅助软件 编辑:程序博客网 时间:2024/06/18 07:39

this在js编程中经常遇到,新手会对this的归属有些迷茫,其实很简单,this的指向就是它的调用对象。

js中程序员的迷茫,this的归属问题

this的归属问题

//控制台

this.x=3;

x//3;

window.x//3;

此时的this就是指window,调用x,其实就是调用window.x。

function d(){this.me=123;this.na=function(){console.log('this:'+this)};console.log('this:'+this)}

var a=new d();

d()//this:[object Window]

a.na()//this:[object Object]

d()this指向window;

a.na调用this指向对象a。

还有很多例子仔细分析this始终指向调用他的那个对象。

js中程序员的迷茫,this的归属问题

this的归属问题

谢谢关注。