four forms of existence of the function:1. Function Form2. Method shape assigns a function to a member of an object, then called a method3. Constructor morphology4. Context Patterns
1. Function Pattern:
var function () { alert (this); // This is window};
2. Method Morphology:
o = {};o.foo = foo; // assign the function foo to the Foo property of Object o o.foo (); // Popup is an object, this represents the object
var lib = { test:function() { alert (this); // This represents the object (the Lib object itself) // var = this; To think of the anonymous function in this representation of the Lib object, you can do so (function() { alert (this); // the anonymous function here does not belong to the Lib object, so this still represents the window })(); }}; Lib.test ();
3. Constructor (constructor)
1, new creates the object and opens up space
2, passing the reference address of the object to the function, using this in the function to receive the
3, Construct method execution end, return this
var person = function () { this . Age = 19 this . Name = "Mr Jing" ; return "{}" ;}; var p = new person (); alert (p.name); // pop up undefined, because the function returns an object, So the object is returned directly to the person, ignoring the Age,name property
var person = function () { this . Age = 19 this . Name = "Mr Jing" ; return 123 var p = new person (); alert (p.name); // popup "Mr Jing", because the return value is not an object, the return value is ignored directly Alert (p); // popup object
The things that change are:
The function's return value is changed by the constructor;
If the return value of a function is an object, it is returned by the return value;
If the return value is not an object, the return value is ignored, and this is returned directly;
4. Context Invocation Mode
Function. Apply (object, [parameter list])
var function (A, b) { alert (this); return a > B? a:b;}; var num = foo1.apply (null, [+]); // at this point the foo1 is a function form, this means windownum = foo1.apply ({}, [in A.]); // at this point foo1 is the method shape, this represents the object passed in the parameter {}
Function. Pager (object, parameter list);
var num1 =foo1.call (null, 112,34); Num1=foo1.call ({},112,34); In addition to the parameter list, the rest is the same as apply
Four kinds of existence patterns of JavaScript functions