美文网首页
JavaScript上下文指针this

JavaScript上下文指针this

作者: 报告老师 | 来源:发表于2017-12-14 19:11 被阅读11次

不知道怎么解释,直接上伪代码

1.var pet={

  name:’miao’,

  talk:function(){

    console.log(this.name);

    console.log(this===pet);

    }

}

pet.talk();

输出结果:miao,true

说明这种情况下,this指向本层对象作用域,就是pet

2.function pet(name){

  this.name=name;

    console.log(this.name);

    console.log(this===global);

}

pet(‘miao’);

输出结果:miao,true,说明这样直接调用一个没有实例化的全局对象输出的this结果是global对象。

3.function pet(name)

    this.name=name;

    this.talk =function(){

    console.log(this.name);

    console.log(this);

  }

}

var cat =new pet(‘miao’);

cat.talk();

这里的this指向实例cat

输出结果:miao,cat对象的json格式

说明通过构造函数实例化以后,因为是通过挂载的函数输出的,所以this指向的是实例本身

相关文章

网友评论

      本文标题:JavaScript上下文指针this

      本文链接:https://www.haomeiwen.com/subject/aaclwxtx.html