首頁  >  文章  >  web前端  >  JS中this指向的幾種函數呼叫方法的介紹

JS中this指向的幾種函數呼叫方法的介紹

不言
不言轉載
2018-11-12 16:20:442273瀏覽

這篇文章帶給大家的內容是關於JS中this指向的幾種函數呼叫方法的介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

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

作為物件的方法呼叫

當函數作為物件的方法被呼叫時,this指向該物件:

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:

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

以上是JS中this指向的幾種函數呼叫方法的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除