【亡羊补牢】JS灵魂之问 第25期 修炼内功 重新探究 this 指向问题

引言

本篇要讲解的内容是关于 重新探究 this 指向问题 ,那今天这篇看能不能问倒你了,一起来探索一下吧。

仰望星空的人,不应该被嘲笑

垃圾回收机制

垃圾回收机制就是负责管理代码执行过程中使用的内存。

原理:

第一步,找出不再使用的变量
第二步,释放其占用内存
第三部,固定的时间间隔运行

重新探究 this 指向问题

第一题

开门见山,我们来看看下面会打印什么?

function test(){
    
    
  this.a = 1;
  console.log(this);
  console.log(this.a);
}
test();
console.log(a);

答案是 window 1 1,不难发现,这个 this是指向 window的。

第二题

继续,看看下面代码又会输出什么?

var a = 1;
function test() {
    
    
  console.log(this);
  console.log(this.a);
}
test();

答案是 window 1,和上题类似。

第三题

继续,又会有怎样的输出呢?

function test(a){
    
    
  this.a = a;
  console.log(this.a);
  console.log(window.a);
}
test(1);

答案是 1 1

第四题

稍微改一下上面代码,又会输出什么呢?

function test(a){
    
    
  this.a = a;
  console.log(this.a);
  console.log(window.a);
}
new test(1);

答案是 1 undefined,因为 window底下并没有 a这个变量。

第五题

接下来,我们再来看看这道题,会打印什么呢?

function test(a){
    
    
  this.a = a;
  console.log(this.a);
}
var a = 223;
test.prototype.say = function(){
    
    
  console.log(this.a);
}
test.prototype.say();

答案是 undefiend,是不是很惊讶?为什么呢?我明明都访问了原型上的say方法,而且全局都有 a变量,为啥呢?

我们不妨打印一下 this,看指向谁。

function test(a){
    
    
  this.a = a;
  console.log(this.a);
}
var a = 223;
test.prototype.say = function(){
    
    
  console.log(this.a);
  console.log(this);
}
test.prototype.say();

然后发现在原型上打印 this,发现指向的是那个函数,而函数如果没有返回值的话,默认会返回 undefined,当然.a也会打印 undefined

第六题

于是我们修改一下代码:

function test(a){
    
    
  this.a = a;
  console.log(this.a);
}
var a = 223;
test.prototype.say = function(){
    
    
  console.log(a);
}
test.prototype.say();

答案是 223

第七题

因此在函数没有实例化的时候,原型上 say方法 this还是会指向那个函数。那么我们再次修改一下,看看下面代码会输出什么

function test(a){
    
    
  this.a = a;
}
var a = 223;
test.prototype.say = function(){
    
    
  console.log(this.a);
}
var t = new test(1);
t.say();

答案是 1,实例化了之后,原型上 say方法的 this 指向了实例对象。

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小狮子前端の笔记仓库

访问超逸の博客,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/108682062