this作为构造函数时注意点

在 JS 中,为了实现类,我们需要定义一些构造函数,在调用一个构造函数的时候加上 new 这个关键字:

function Person(name) {
   this.name = name;
   console.log(this);// Person
}

var p1 =new Person('aa');

此时,this 指向这个构造函数调用的时候实例化出来的对象。

当然了,构造函数其实也是一个函数,若将构造函数当做普通函数来调用,this 指向 Window

function Person(name) {
   this.name = name;
   console.log(this);// Window
}
var p2 =Person('bb');

  

猜你喜欢

转载自www.cnblogs.com/samsara-yx/p/10135003.html