通过javascript 函数的调用方式来理解"this"

前言
    很多初学者会对 javascript 中的 this 的指向感到迷惑, 其实只要理解了 javascript 中函数的调用方式, 就不难理解 this 了
 
原生调用是最基本的函数调用方式
在 javascript 中, 函数一共有四种调用方式:
  • 简单调用
  • 对象成员函数调用
  • new 调用
  • 所有的函数调用都能够写成以下形式, 我们称之为原生调用, 也是第四种调用方法
fn.call(this, args...) // 或者, fn.apply(this, argsArray)
    • fn 代表被调用的函数,
    • call 是 javascript 语言自带的 Function 类的原生方法,
    • this 为调用 fn 的环境
    • args 为电泳 fn 时传入的参数
 
接下来, 试着把前三种函数的调用方式改写成原生调用, 顺便探讨每种调用方式中, this的指向
 
简单的函数调用
// 在全局换进中定义 fn
function fn(arg){
  console.log(this) // 使用了this
  //...
}
 
 
fn(arg)
 
// 写成原生调用 
// fn.call(window, arg) // 此时 this 指向 window // 在es5严格模式下, 相当于 fn.call(undefined, arg) // 此时 this 指向 undefined

 

 
对象的成员函数调用
var person = {
  name: "Brendan Eich", 
  hello: function(thing) { 
    console.log(this + " says hello " + thing)
  }
}
 
person.hello("world") 
// 写成原生调用
// person.hello.call(person, "world")    // 此时, this 指向person
 
 
new 调用
function Person(){
  this.name = 'zhao'
}
var person = new Person()
 
// 写成原生调用
function createPerson(){
  var obj = {}
  obj.__proto__ = Person.prototype
  Person.call(oj)                        // 此时, this 指向 obj
  return obj
}
 
varperson = createPerson()

 

 
posted @ 2017-07-06 13:51  预兆ZeD  阅读(169)  评论(0编辑  收藏  举报