Selected topics and explanations pointed to by this

1. What does the following code output? (The content is reprinted, and the address is as follows: https://blog.csdn.net/joyvonlee/article/details/94622491?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute. pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase )

let length = 10;
function fn() {
	console.log(this.length);
}
 
var obj = {
	length: 5,
	method: function(fn) {
		fn();	
		arguments[0]();		
		
	}
}
 
obj.method(fn, 1);

 The output is as follows:

      

The explanation is as follows: 

First look at the code execution, obj.method(fn, 1);
The method in the obj object is a function. When the fn() inside it is executed, the default binding rule of this is applied (click here to see why the default is applied Binding rules) , so this points to window
window.length is equal to 0, so 0 will be output when this line of statement is executed.
Some people may ask, doesn't the global scope declare a length object? Why not output 10?
The reason is that the length object is declared using the let keyword, it is not a property of the global window object, so window.length and it (let length = 10) are two different objects. This is a pit! (Emphasis!!!)

The next step is to execute arguments[0](); The 
arguments object is a class array, and its 0th subscript is the first parameter of the argument list, which is the fn function.
When the fn function is called, its this is bound to the arguments object.
Because obj.method passes in two parameters, the length attribute of the arguments object is 2

 

Guess you like

Origin blog.csdn.net/L_Z_jay/article/details/109145549