javascript - 请教一个js中new构造函数中子函数的this问题-,-
本文介绍了javascript - 请教一个js中new构造函数中子函数的this问题-,-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
function F1(){
function f2(names){
this.name=names;
alert(this);//window,!为什么这里this会指向window?F1在后面是用new构造函数的形式实例化instance不是作为普通函数执行啊!//
}
f2("nicholas");
this.age=29;
alert(this);//Object 这个我理解,这是new的特性,this指向instance//
}
var instance=new F1();
console.log(instance.name);//undefined,因为上面F1中没赋到值//
console.log(instance.age);//29//
console.log(window.name);//nicholas//
解决方案
在你的f2方法中没有指定是否是严格模式,其中的this默认就指向了window,然后直接this.name就修改了window.name的值。
就这样。
给你篇我的博客文章,加深你的理解。
js中this的一些总结
这篇关于javascript - 请教一个js中new构造函数中子函数的this问题-,-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文