JS– this

this简介

  this是JS中很重要的一个关键字,它总是指向一个对象,

  而这个对象是在运行时基于函数的执行环境动态绑定的。

 

this指向分类

  作为普通函数调用

  作为构造函数调用

  作为对象的方法调用

  call和apply调用

 

  作为普通函数调用

    当函数以普通函数的方式调用时,函数内的this在非严格模式下指向window,在严格模式下指向undefined

var name = “global”;var person = { name: "tom", sayName: function () { console.log(this.name); } }var printName = person.sayName;printName(); //global

     如上代码是以普通函数的方式调用函数

 

  作为构造函数调用

    当函数通过new调用时,即以构造函数的方式调用,函数会返回一个对象,函数内部的this指向这个返回的对象

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

var person = new Persosn("tom"); //{name: "tom"}

 

  

  作为对象的方法调用

    当函数作为某个对象的属性时,函数内部的this指向这个对象

var person = { name: "tom", sayName: function () { console.log(this.name); } }

persosn.sayName(); //"tom"

 

  

  call和apply调用

    通过call,apply的方式调用函数,可以动态的改变传入函数中的this指向

var sayName = function () {
  console.log(this.name);
}

var person1 = {
  name: "tom"
}
var person2 = {
  name; "lily"
}

sayName.call(person1); //"tome"
sayName.call(person2); //"lily"

 

相关文章