js中对this的理解

96 阅读1分钟

//1.函数预编译过程中 this --> window

//AO  this: window

function test() {

  console.log(this)

}

test()  //window

//2.全局作用域里 this --> window

//GO  this: window

console.log(this)  //window

//3.call/apply可以改变函数运行时this指向

var obj = {}

function Person(name, age) {

  this.name = name

  this.age = age

}

Person.call(obj, 'lyj', 18)

// Person.apply(obj, ['lyj', 18])

console.log(obj)  //{name: "lyj", age: 18}

//4.obj.func(), func()里面的this指向obj

var obj = {

  a: function() {

    console.log(this.name)

  },

  name: 'abc'

}

obj.a()  //abc

\


var name = '222'

var a = {

  name: '111',

  say: function() {

    console.log(this.name)

  }

}

var fun = a.say

fun()    //222  没有被谁调用, this指向window

a.say()  //111  被a调用, this指向a

var b = {

  name: '333',

  say: function(fun) {

    fun()  //没有被谁调用, fun里面的this指向window

  }

}

b.say(a.say)  //222 

b.say = a.say

b.say()  //333  被b调用, this指向b