In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the ways of binding this in JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Four binding rules of this
1. Default binding
This is the most commonly used type of function call: stand-alone function calls (that is, functions are called directly with undecorated function references). You can think of this rule as the default rule when other rules cannot be applied.
The default bound this points to window in non-strict mode and to undefined in strict mode, for example, the following function foo is in non-strict mode:
Var a = 2 X function foo () {var a = 3; console.log (this.a);} foo (); / / 2
The this in the foo () method here points to window, so window.a = 2
In strict mode, this. Point to undefined, so accessing this.a will result in an error:
Var a = 2X function foo () {"use strict"; var a = 3; console.log (this.a);} foo (); / / Uncaught TypeError: Cannot read property 'a'of undefined
two。 Implicit binding
If there is a context object at the call location, or if it is "owned" or "included" by an object, implicit binding is used.
Function foo () {console.log (this.a);} var obj = {a: 2, foo: foo}; obj.foo (); / / 2
The foo in the above example is called through obj.foo (), and the calling location refers to the function using the obj context, so the this in foo points to obj.
In addition, foo is added to obj as a reference, but whether it is defined directly in obj or first defined and then added as a reference attribute, foo strictly does not belong to obj, so the "have" and "include" in the above definition are in quotation marks, so it is easy to understand.
Common implicit invocation scenarios:
Obj.fn (); arguments [I] (); / / actually changes the calling mode of the point to [] calling el.onClick (function () {console.log (this); / / this pointing to el}).
Implicit loss
Let's take a look at a piece of code:
Function foo () {console.log (this.a);} var obj = {a: 2, foo: foo}; var bar = obj.foo; / / function alias! Var a = "global"; / / an is the property of the global object bar (); / / "global"
The above code actually only looks at the way the call is called: bar (), which is actually a function call without any modification, so the default binding is applied.
There is another way of passing parameters that can also be implicitly lost, and the principle is the same as in the above example:
Function foo () {console.log (this.a);} function doFoo (fn) {/ / fn actually refers to foo fn (); / / {/ / this inherits from foo () console.log (this.a);};} var obj1 = {aVl2}; var obj2 = {aV3}; var bar = foo.call (obj1); bar.call (obj2); / / 2, not 3!
The arrow function created inside foo () captures the this of foo () when it is called. Because the this of foo () is bound to the this of obj1,bar (referencing the arrow function) is also bound to obj1, the binding of the arrow function cannot be modified. (not even new! )
A few examples to deepen our understanding
This's theoretical knowledge has been explained almost, let's give a few examples to see if you have a comprehensive understanding:
1. Classic interview questions: what is the following output?
Var length = 10 function fn () {console.log (this.length);} var obj = {length: 5, method: function (fn) {fn (); arguments [0] ();}}; obj.method (fn, 1)
Fn is called twice in the method method in obj. The first time is to call the "naked" fn directly, so the this in fn () uses the default binding, and the this.length is 10. 0. When the second call is called through arguments0, arguments [0] actually points to fn, but it is implicitly bound through obj [FN] object context, so this points to arguments, while arguments has only one item (there is only one parameter in method), so arguments.length is 1. So the printed result is:
one hundred and one
two。 What is the following output?
Var obj = {birth: 1990, getAge: function () {var b = this.birth; / / 1990 var fn = function () {return new Date () .getFullYear ()-this.birth; / / this points to window or undefined}; return fn ();}}; obj.getAge ()
The answer is that errors will be reported in strict mode and NaN will be output in non-strict mode.
The reason is also that after calling obj.getAge (), the this in the getAge method uses implicit binding. But return fn () uses "naked fn" with the default binding, and the this in fn points to window or undefined.
Use the arrow function to correct the direction of this:
Var obj = {birth: 1990, getAge: function () {var b = this.birth; / / 1990 var fn = () = > new Date (). GetFullYear ()-this.birth; / / this points to the obj object return fn ();}}; obj.getAge (); / / 25
After using the arrow function, the this in fn is determined in his lexical analysis phase (that is, when fn is defined), regardless of the location of the call. The this of fn points to the outer scope (that is, this in getAge)
3. Why is the following output 'luo'
Var A = function (name) {this.name = name;}; var B = function () {A.apply (this,arguments);}; B.prototype.getName = function () {return this.name;}; var b=new B ('sven'); / / B {name: "luo"} console.log (b.getName ()); / / output:' luo'
After executing new B ('seven'), a new object b is returned, and the this in the B function is bound to the new object b. When the function body of B executes A.apply (this.arguments), that is, when b.name = name; is executed, the value of b is {name:'luo'}, so b.getName () can output' luo' ~
This is the end of the content of "what are the ways to bind this in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.