Home  >  Article  >  Web Front-end  >  Introduction to function calling and this pointing in JavaScript (code)

Introduction to function calling and this pointing in JavaScript (code)

不言
不言Original
2019-03-21 11:25:372474browse

This article brings you an introduction (code) about function calls and this pointing in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Function calling and this pointing

1. Ordinary function calling this points to window

function fn() {
    console.log(this);
}
window.fn();

2. Method calling this points to the object calling the method

var obj = {
    fun: function () {
        console.log(this);
    }
}
obj.fun();

3. As a constructor call, this inside the constructor points to the object created by the constructor

var gf = {
    name : "tangwei",
    bar : "c++",
    sayWhat : function() {
        console.log(this.name + "said:love you forever");
    }
}

4. As an event handler, the object that triggers the event

btn.onclick = function () {
    console.log(this);
}

5. As the parameter of the timer, this points to window

setInterval(function() {
    console.log(this);
}, 1000);

Summary: The this inside the function is determined when the function is called.

This article is all over here. For more other exciting content, you can pay attention to the JavaScript Tutorial Video column on the PHP Chinese website!

The above is the detailed content of Introduction to function calling and this pointing in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn