Article From:https://segmentfault.com/q/1010000012145930
Question:

The code is as follows:

var body = document.querySelector('body');
body.style.background = '#000';
console.log(body.style.background);
//    "rgb(0, 0, 0)"
body.style.background.substr(this.length);
//    "gb(0, 0, 0)"

What is the this pointing to in this case? Alone, log can’t find 1 length objects.

PS: Originally intended to simplify the corresponding code, substr is used to filter.px|vhEqual unit

Answer 0:

The function is called directly, and this points to the undefined. When the object is called, the this points to the object. In non strict mode, when this points to undefined, it automatically changes to window. Your code is here to call this directly, and it is notStrict mode, so point to window., you can look at your console.log (this).

Answer 1:

I think you should take a closer look at the parameters of the substr method and the return value.

Answer 2:

If you put it directly in script, this means window, you can.

    window.length = 2;
    console.log(body.style.background.substr(this.length));

Answer 3:

yeswindowAlengthattribute

MDN

Answer 4:

thisIt’s window. Out of this sentenceconsole.log(this);It is found in the window property that its length is 0

Answer 5:

thisPoint to window;

var _color = body.style.background;
    _color.substr(color.length); 

Answer 6:

In JS, this refers to the object that calls the function, such as
div1.onclick = function (){

this.innerHTML = 'I'm DIV1'

}
thisFor div1
In your code, this points to the root node of window DOM.

Leave a Reply

Your email address will not be published. Required fields are marked *