原生JS中this的指向

110 阅读1分钟
(1)
function a() {
  console.log( this === window)
}
a()		// true

(2)
var b = {
  c: 2,
  d: function () {
  	console.log( this )
  }
}
b.d()	 // b这个对象

(3)
var b = {
  c: 2,
  d: function () {
      function e() {
          console.log(this)
      }
      e()
  }
}
b.d()	 // Window对象

(4)
var o = {
 s: function() {
 		console.log(this)
 }
}
var f = o.s		// 此时o.s没有被调用执行
f()		// Window对象

// 函数是对象,对象是按引用传递的。o.s赋值给变量f,相当于把o.s函数指向了
// 变量f,并且在f变量处调用,而变量f其实是Window对象的属性

(5)
function a() {
	this.b = 333
    console.log(this)
}
new a()			// this指向new出来的新对象

// new关键字改变了函数内this的指向,使其指向刚创建的对象

(6)
<div id='btn'>按钮</div>

btn.onclick = function() {
	console.log(this)		// <div id='btn'>按钮</div>
}

总结:
	函数内部的this,是在函数调用时确定其指向的