four modes of JS method invocation1. Method Invocation Mode
1 functionpersion () {2 varname1 = "Itcast",3Age1 = 19,4Show1 =function() {5Console.log ( This. Name);6 };7 8 return {9 Age:age1,Ten name:name1, One Show:show1 A }; - } - the varp =Newpersion (); - p.show (); //The this in the Show method points to the P object. 2. function call mode
1 function Add (A, b) {2 this. result = a + b; 3 }45 Add (3, 9); // when this method executes, this points to the window 6 7 Console.log (result);
3. constructor Invocation mode
1 functionpersion () {2 This. Name = "123";3 This. Age = 19;4 This. Show =function(){5Console.log ( This. Name);6 };7 }8 9 varp =Newpersion ();Ten p.show ();//in the Show method, method this, which points to the P object instance.
4.call and apply mode
1 functionAdd (A, b) {2 This. result = A +B;s3 }4 5 varp = {};//defines an empty object. 6Add.call (p,3,4); //when this method is called, this points to the P7 Console.log (p.result);8 9 //apply and call are the same usage, except that the second argument is passed with an array.
variable Promotion : Before the function executes, all the variables in the function are moved to the first declaration.
function Name Promotion scripts in script , before executing, will first compile all the functions in the script to parse, and then execute the normal js code.
Day 164th: Four modes of JS method invocation