This is a very important keyword in Javascript. The correct use of this can improve the efficiency of our program. Before, there were some misunderstandings about this. Today, AFTER reading an article, I have some in-depth understanding.

 

Owner of this.

In general, this refers to the function itself being executed, or to the object that the function belongs to. Such as

function dosomething(){

this.style.color = ‘red’; \

} \

When the function executes, this refers to the window object. And:

var dosomething = function(){

this.style.color = ‘red’; \

} \

This refers to the object dosomething;

Unfortunately, the window object has no style property, so the dosomething function will cause an error if executed directly. To apply this correctly, we need to copy the function onto the object’s properties. \

For example: element.onclick = dosomething;

To summarize, examples of correct use of this by copying are: \

element.onclick = dosomething;

element.addEventListener(‘click’,dosomething,false); \

element.onclick = function(){ this.style.color = ‘red’; };

<element onclick=’javascript:this.style.color = red; ‘/ > \

Examples of using this by direct reference:

element.onclick = function(){ dosomething(); }; \

element.attachEvent(‘onclick’,dosomething);

<element onclick = “dosomething();” / > \

Such a reference, this, will be referred to the window object and will fail, so it should be noticed in normal applications. \