请教一个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//
阅读 2.2k
3 个回答

在你的f2方法中没有指定是否是严格模式,其中的this默认就指向了window,然后直接this.name就修改了window.name的值。

就这样。

给你篇我的博客文章,加深你的理解。
js中this的一些总结

因为你的f2方法没有实例化,所以this指向的是window。如果你想将this指向F1实例的话你可以用call/apply来调用。

f2.call(this, "nicholas");
f2.apply(this, ["nicholas"]);

this的几种调用
f2属于函数调用,默认指向全局(这个 js作者规定的,你只能这样记住它)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题