天天看点

JavaScript this全解析

​JavaScript​

​​中的​

​this​

​只有如下几种情况,并按他们的优先级从低到高划分如下:

独立函数调用,例如

​getUserInfo()​

​​,此时

​​

​this​

​​指向全局对象

​​

​window​

对象调用,例如

​stu.getStudentName()​

​​,此时

​​

​this​

​​指向调用的对象

​​

​stu​

​call()​

​​、

​​

​apply()​

​​和

​​

​bind()​

​​改变上下文的方法,

​​

​this​

​​指向取决于这些方法的第一个参数,当第一个参数为

​​

​null​

​​时,

​​

​this​

​​指向全局对象

​​

​window​

箭头函数没有

​this​

​​,箭头函数里面的

​​

​this​

​​只取决于包裹箭头函数的第一个普通函数的

​​

​this​

​new​

​​构造函数调用,

​​

​this​

​永远指向构造函数返回的实例上,优先级最高。
var name = 'global name';
var foo = function() {
  console.log(this.name);
}
var Person = function(name) {
  this.name = name;
}
Person.prototype.getName = function() {
  console.log(this.name);
}
var obj = {
  name: 'obj name',
  foo: foo
}
var obj1 = {
  name: 'obj1 name'
}

// 独立函数调用,输出:global name
foo();
// 对象调用,输出:obj name
obj.foo();
// apply(),输出:obj1 name
obj.foo.apply(obj1);
// new 构造函数调用,输出:p1 name
var p1 = new Person('p1 name');
p1.getName();      

this解析流程图

继续阅读