javascript之this

MDN關於this的描述app

全局上下文

在全局運行上下文中(在任何函數體外部),this指代全局對象,不管是否在嚴格模式下函數

console.log(this.document === document);//true
console.log(this === window); //true
this.a = 22;
console.log(window.a); //22

函數上下文

在函數內部,this的值取決於函數是如何調用的ui

直接調用

function f1() {
    return this;
}
f1() === window; //true
  
function f2() {
    "use strict";
    return this;
}
f2() === undefined; // true
在嚴格模式下,this是進入運行環境時設置的

對象方法中的this

var o = {
    prop: 22,
    f: function() {
        return this.prop;
    }
};
console.log(o.f());//22

原型鏈中的this

var o = {
    f: function(){
        return this.a + this.b;
    }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;
console.log(p.f()); //5

call和apply

經過call()和applly(),能夠將this綁定在一個指定的對象上this

function add(c,d){
    return this.a + this.b + c + d;
}
var o = {a:1, b:3};
add.call(o,5,7);
add.apply(o,[5,7]);

bind方法

調用f.bind(someObject)會建立一個與f具備相同函數體和做用域的函數,可是在這個新函數中,this將永久地被綁定到了bind的第一個參數,不管這個函數是如何被調用的。code

function f(){
    return this.a;
}

var g = f.bind({a:'azerty'});
console.log(g());//azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g());//37 azerty

DOM事件處理函數中的this

this指向觸發事件的元素對象

// 被調用時,將關聯的元素變成藍色
function bluify(e){
  console.log(this === e.currentTarget); // 老是 true

  // 當 currentTarget 和 target 是同一個對象是爲 true
  console.log(this === e.target);        
  this.style.backgroundColor = '#A5D9F3';
}

// 獲取文檔中的全部元素的列表
var elements = document.getElementsByTagName('*');

// 將bluify做爲元素的點擊監聽函數,當元素被點擊時,就會變成藍色
for(var i=0 ; i<elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}

內聯事件處理函數中的 this

當代碼被內聯處理函數調用時,它的this指向監聽器所在的DOM元素:事件

<button onclick="alert(this.tagName.toLowerCase());">
  Show this
</button>
相關文章
相關標籤/搜索