Home > Web Front-end > JS Tutorial > Briefly explain the use of this in js through a piece of code_Basic knowledge

Briefly explain the use of this in js through a piece of code_Basic knowledge

WBOY
Release: 2016-05-16 17:28:05
Original
1102 people have browsed it

Today, a friend said that he encountered the following code and asked me to explain the reason

Copy the code The code is as follows:

var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this. name;
};
}
};

alert(object.getNameFunc()()); The reason is that this of js is determined dynamically, and how you call it There is a direct relationship.

Simply put, if you use the "object.function name" method when calling a function, then this is the object before the . (dot), otherwise it is window.
For example, when you call object.getNameFunc(), this in the getNameFunc function body is the object you just declared. If you write
copy the code the code is as follows:

var func = object.getNameFunc;
func();

At this time, this in the getNameFunc function body is window, although the difference in calling the same function determines the difference in this.
Similarly, object.getNameFunc() returns a function reference. Adding parentheses allows the function to be executed. In fact, it is equivalent to the following code
Copy the code The code is as follows:

var func = object.getNameFunc( );
alert( func() );

There is no "object." form before the function, so when executing the function, this is window, and the result is obvious.

I will write an article about js this in the future. Everyone is welcome to follow my CSDN blog tt361.
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template