Related questions about this

jacklove
Release: 2018-05-21 13:35:29
Original
1097 people have browsed it

I often encounter this problem in my studies. This article will explain its related issues.

Several cases of this as the global object window

This as a function call

This as an internal nested function

In setTimeout, setInteval this is still a global variable window

Several cases when this is a non-global variable

Constructor (the constructor generates a new object through a function, at this time this refers to this new object )

Called as an object method, such as:

var obj1 = { name: 'Byron', fn : function(){ console.log(this); } }; obj1.fn(); // obj1var fn2 = obj1.fn; fn2(); //此时this仍然指的是全局对象window
Copy after login

DOM object binding event this represents the source DOM object (there are bugs in lower versions of IE and also points to window)

Use the bind function to bind the original function. At this time, this refers to the first parameter passed into bind. For example:

var obj1 = { name: 'Byron', fn : function(){ console.log(this); } }; obj1.fn(); //obj1var fn2 = obj1.fn;
Copy after login
fn2(); //此时this仍然指的是全局对象windowvar fn3 = obj1.fn.bind(obj1);fn3(); //此时this指的为obj1(此方法比较灵活,可利用此方法将所要传送给this 的参数指定为bind的第一个对象) apply和call设置this,如: fn.call(context,num1,num2...);fn.apply(context,numArray)
Copy after login

The first parameter is this object. The difference is that call accepts a parameter list and apply accepts a parameter array.

caller, if a function f is called in the global scope, f.caller is null. On the contrary, if a function is called in another function scope, f.caller points to the call Its function can be simply understood as caller refers to its parent function. For example:

function fn(){ console.log(fn.caller); function fn2(){ console.log(fn2.caller) } fn2() }
Copy after login
fn(); callee,当函数被调用的时候arguments.callee(匿名函数的时候很好用,可以调用自身) var i = 1;window.onclick = function(){ console.log(1); if(i<5){ i++; setTimeout(arguments.callee,200); }}
Copy after login

This article explains the related issues of this. For more related content, please pay attention to the php Chinese website.

Related recommendations:

JS arrays, strings and mathematical functions

About JS time objects and recursion issues

Some CSS styling basics

The above is the detailed content of Related questions about this. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
Why is "this" defined as undefined in Vue 3 function Please look at the following simple component example in Vue3: