影響JavaScript中this指向的幾種函數調用方法

前言

初學javascript總會對this指向感到疑惑,想要深刻學習javascript,必須先理清楚和this相關的幾個概念。javascript中this老是指向一個對象,但具體指向誰是在運行時根據函數執行環境動態綁定的,而並不是函數被聲明時的環境。除去不經常使用的with和eval的狀況,具體到實際應用中,this指向大體能夠分爲如下4種。javascript

做爲對象的方法調用

當函數做爲對象的方法被調用時,this指向該對象:java

var person = {
  name: 'twy',
  getName: function() {
    console.info(this === person);  // 輸出true
    console.info(this.name);     // 輸出twy
  }
}
person.getName();

做爲普通函數調用

當函數做爲普通的函數被調用時,非嚴格模式下this指向全局對象:瀏覽器

function getName(){
  // 非嚴格模式
  console.info(this === window); // 瀏覽器環境下輸出true
}
getName();

嚴格模式下this爲undefined:app

function getName(){
  // 嚴格模式
  "use strict"
  console.info(this === window); // 輸出false
}
getName();

構造器調用

當new一個對象時,構造器裏的this指向new出來的這個對象:函數

function person(){
  // 構造函數
  this.color = 'white';
}
var boy = new person();
console.info(boy.color);  // 輸出white

call或apply調用

Function.prototype.applyFunction.prototype.call 能夠動態改變傳入函數的this指向:學習

// 聲明一個父親對象,getName方法返回父親的名字
var father = {
  name: 'twy',
  getName: function(){
    return this.name;
  }
}
// 生命一個兒子對象,可是沒有返回名字的功能
var child = {
  name: 'chy'
}
console.info(father.getName()); // 輸出twy

// 使用call或apply將father.getName函數裏this指向child
console.info(father.getName.call(child)); // 輸出chy
console.info(father.getName.apply(child)); // 輸出chy

下一篇文章我將重點介紹call和apply。this

最後

將this理解透徹,是一個jser必需要作的事情。prototype

相關文章
相關標籤/搜索