JS 基礎 #2 | This

this

console.log(this);
// Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

this 於一般 function中 (Regular function call)

calculateAge(1985);

function calculateAge(year) {
    console.log(2016 - year);    
    console.log(this);           
}
// 31
// Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

this 於物件中 (Method Call)

var john = {
    name: 'John',
    yearOfBirth: 1990,
    calculateAge: function() {
        console.log(this);
        console.log(2016 - this.yearOfBirth);
    }
}
john.calculateAge();
// {name: "John", yearOfBirth: 1990, calculateAge: ƒ}
// 26

this 於物件的一般 function 中

var john = {
    name: 'John',
    yearOfBirth: 1990,
    calculateAge: function() {
        console.log(this);
        console.log(2016 - this.yearOfBirth);
        
        function innerFunction() {
            console.log(this);
        }
        innerFunction();
    }
}
john.calculateAge();
// {name: "John", yearOfBirth: 1990, calculateAge: ƒ}
// 26
// **Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}**

Zeen is a next generation WordPress theme. It’s powerful, beautifully designed and comes with everything you need to engage your visitors and increase conversions.