Skip to content

this? 函数执行的主体,谁把函数执行的,那么this就是谁,函数执行的主体和函数在哪创建、在哪执行都没啥关系 全局的this是window(GO),块级私有上下文中没有自己的this,遇到的this是"宿主环境"中的 我们研究的this都是指函数执行产生的私有上下文中的this

1.给当前元素的某一个事件行为绑定方法,当事件行为触发,浏览器会帮我们把绑定的方法执行, 此时方法中的this是当前操作的元素本身 document.body.onclick = fn // this => document.body

2.函数执行,看函数前面是否有'.' 有'.' '.'前面是谁this就是谁 没'.' this是window / undefined

3.箭头函数的this是上级上下文中的this

4.new一个构造函数,构造函数中的this是创建的实例对象

5.可以基于Function.prototype上的call/apply/bind改变this指向

js
"use strict"
fn() // this => undefined
obj.fn() // this => obj
let arr = [10, 20],
push = arr.push
push() // => this => undefined
arr.push() // this => arr
arr.__proto__.push() // this => arr.__proto__
Array.prototype.push() // this => Array.prototype
arr.__proto__.__proto__.hasOwnProperty() // this => arr.__proto__.__proto__
document.body.onclick = function () {
  // this => document.body
  fn() // this => undefined
}
(function () {
  // this => undefined
})()
js
// example
let obj = {
  fn: (function () {
    console.log(this)
    return function () {
      console.log(this)
    }
  })()
}
obj.fn()

// example1
let x = 3,
  obj = {
    x: 5
  }
obj.fn = (function () {
  this.x *= ++x
  return function (y) {
    this.x *= (++x) + y
    console.log(x)
  }
})()
let fn = obj.fn
obj.fn(6)
fn(4)
console.log(obj.x, x, window.x)

// example2
var fullName = 'language'
var obj = {
  fullName: 'js',
  props: {
    getFullName: function () {
      return this.fullName
    }
  }
}
console.log(obj.props.getFullName())
var test = obj.props.getFullName
console.log(test())

// example3
var name = 'window'
var Tom = {
  name: 'Tom',
  show: function () {
    console.log(this.name)
  },
  wait: function () {
    var fun = this.show
    fun()
  }
}
Tom.wait()

// example4
var num = 10
var obj = {num: 20}
obj.fn = (function () {
  this.num = num * 3
  num++
  return function (n) {
    this.num += n
    num++
    console.log(num)
  }
})(obj.num)
var fn = obj.fn
fn(5)
obj.fn(10)
console.log(num, obj.num)

// example
window.val = 1 
var json = {
  val: 10, 
  dbl: function () {
    this.val *= 2
  }
}
json.dbl()
var dbl = json.dbl
dbl()
json.dbl.call(window)
alert(window.val + json.val)

// example
(function () {
  var val = 1
  var json = {
    val: 10,
    dbl: function () {
      val *= 2
    }
  }
  json.dbl()
  alert(json.val + val) 
})()

// example
function fun () {
  this.a = 0,
  this.b = function () {
    alert(this.a)
  }
}

fun.prototype = {
  b: function () {
    this.a = 20
    alert(this.a)
  },
  c: function () {
    this.a = 30
    alert(this.a)
  }
}
var my_fun = new fun()
my_fun.b() 
my_fun.c()