This article mainly introduces the use of this keyword in JavaScript, which is the basic knowledge for getting started with JavaScript. Friends who need it can refer to it
Like many other object-oriented languages, JavaScript also has this keyword, this is used in functions to point to the object that calls this method. In actual programming, to determine who this points to, you can generally follow the following principles:
If the function is called by Function.call or Function.apply, then this points to the first element of call/apply parameter, if the parameter is null or undefined, this points to the global object (in the browser, the global object is the window object).
If the function is called by Function.bind, then this will point to the first parameter of bind (when the method is created).
If the function is called as a method by an object, then this points to this object.
If the function is just called as a function and is not attached to any object, then this points to the global variable window.
Function
First, let’s look at “function”:
function introduce() { alert("Hello, I am Laruence\r\n"); }
For, this function, this Who does the keyword point to?
A function defined globally, the owner of the function is the current page, that is, the window object.
This is why, I put the function in quotes. Because the function defined globally is actually a method of the window object.
Therefore, we can call it directly through the function name, or we can call it through the window. method name. At this time, this in the method The keyword points to its owner: window object.
If we look at the introduce attribute of window, we will get:
var name = "I am Laruence"; function introduce() { alert(this.name); } alert(window.introduce); /** * output: * function introduce() { * alert(this.name); * } */
After reading the above code, you may think Since the global function is a method of the window object, and the global variable is an attribute of the window object (already mentioned in the Javasript scope), then the global variable can be accessed through the this keyword in the global function, right?
The answer is yes, if you call the introduce function, you will know me as Laruence.
Event handling function
Perhaps, you are confused about this keyword, Most of the reasons come from using functions (methods) in event processing.
<input id="name" type="text" name="name" value="Laruence" />
For example, we now need to display the value of the name input box when we click on the "name" input box. Then, you can write the following code:
function showValue() { alert(this.value); } document.getElementById('name').onclick = showValue;
The above code runs normally, but why? Doesn’t it mean that the this pointer of the function always points to the function owner? Doesn’t it mean that the owner of the global variable is the window object? What?
Haha, if you can think of this question, it means you are reading my article seriously. Otherwise, I suggest you read it from the beginning, otherwise you will still be confused after reading it~
Well, yes, for the above code, showValue is defined in the global object, so it seems that the problem can only occur when the onclick event is bound.
We know that everything in Js is Objects, functions and methods are also attributes of objects, but functions have executable internal attributes. Therefore, for the above code, when binding the processor to onclick, it actually binds the input box Dom object with the id of name Assign a value to the onclick attribute.
In other words, we give the function showValue Copy to the onclick attribute of the name input box object. If we look at the onclick at this time:
function showValue() { alert(this.value); } document.getElementById('name').onclick = showValue; alert(document.getElementById('name').onclick); /** * output * function showValue() { * alert(this.value); * } */
So, when When the event is triggered, the onclick method of the name input box will be called. At this time, the this keyword will naturally point to the name input box.
However, confusing things come, such as the following This way of writing:
function showValue() { alert(this.value); } <input id="name" type="text" name="name" value="Laruence" onclick="showValue()"/>
cannot run normally, why is that?
Well, because at this time, it is not an assignment, but a reference.
If We pay attention to two ways of writing onclick. You will find that for the previous method, we used:
dom.onclick = showvalue; //没有调用符
and for the previous method:
onclick = "showvalue()" //有调用符
This can also be used sideways reflects the difference between the two: for the former, it is assignment, while for the latter, it is reference. If we check the onclick attribute of the input box at this time, we get:
alert(dom.onclick); /** * output: * function onclick() { * showValue(); * } */
Do you see the difference? Do you understand why?
Speaking of this, there is a very interesting example. You can try it under IE:
<img src="xxx" onerror="alert(1);} function hi() { alert(2); " />
Change the pointer of this
Well, now that we already know why, how can we make this point to the place we want to point to?
For the above event processing function, we can have the following A way to write:
dom.onclick = showValue(); dom.onclick = function() { alert(this.value) ;} <input onclick="alert(this.value);" /> //想想刚才我们的引用,是如何把这句嵌入的. dom.addEventListener(dom, showValue, false); //ff only
For situations where it is not an event processing function, we can use apply, or call, to change the pointer of this keyword.
For example:
var laruence = { name : 'laruence', age : 26, position : 'Senior PHP Engineer', company : 'Baidu.inc' }; function introduce() { alert(this.name); } introduce.call(laruence);
Example of function being called by Function.call:
var myObject = { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' }; var secondObject = { myName : 'Colin' }; myObject.sayHello(); // logs 'Hi! My name is Rebecca' myObject.sayHello.call(secondObject); // logs 'Hi! My name is Colin'
Example of function being called by Function.call:
var myName = 'the global object', sayHello = function () { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' }; var myObjectHello = sayHello.bind(myObject); sayHello(); // logs 'Hi! My name is the global object' myObjectHello(); // logs 'Hi! My name is Rebecca'
Example of function being called by object:
var myName = 'the global object', sayHello = function() { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' }, secondObject = { myName : 'Colin' }; myObject.sayHello = sayHello; secondObject.sayHello = sayHello; sayHello(); // logs 'Hi! My name is the global object' myObject.sayHello(); // logs 'Hi! My name is Rebecca' secondObject.sayHello(); // logs 'Hi! My name is Colin'
When calling a function in a deep namespace, we usually cache a variable pointing to the function to be called to reduce the amount of code. But doing so will change the value of this in the function and ultimately perform the wrong operation. For example:
var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' } }; var hello = myNamespace.myObject.sayHello; hello(); // logs 'Hi! My name is undefined'
So, if you want to cache variables to save code, the correct way is to save only the object that calls that function:
var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' } }; var obj = myNamespace.myObject; obj.sayHello(); // logs 'Hi! My name is Rebecca'
总之,有一个大原则:谁调用了那个函数,this 就指向谁。
以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程!