引言
本篇要讲解的内容是关于 重新探究 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
指向了实例对象。
最后
文章产出不易,还望各位小伙伴们支持一波!
往期精选:
访问超逸の博客,方便小伙伴阅读玩耍~
学如逆水行舟,不进则退