Four invocation patterns for Javascript functions
1 function mode
Most common function calls
declarative function Functions
fn1 () {
console.log (this);
}
function expression functions
var fn2 = function () {
console.log (this);
In the calling function, this represents the global object, which in the browser refers to Window
fn1 (); Window
fn2 (); Window
2 method mode
The function is attached to an object and is an attribute of the object, and we call this function again. This pattern is the method invocation pattern.
var obj = {
name: ' Zhangsan ',
sayhi:function () {
console.log (this);
}
;
Obj.sayhi (); Obj Object
3 Constructor Call pattern
That is, the call to the constructor, generally through the new + function name (), which is not fundamentally different from the pattern above.
function person () {}
var tom = new Person ();//This is the detailed process of the call
//constructor Call of the constructor function
//1 An object will be created internally o
//2 to assign a value to an object (thi s), and then perform various operations
//3 Returns the return value of this object o
//constructor://// There is a default return value, the newly created object (instance); When the return value is added manually:
// 1. The return value is the base data type--> the true return value or the newly created object (that is, the instance)
// 2. The return value is a complex data type (object)--> The true return value is this object
4 Context Mode
Essence--Object borrows a method (function) that is not part of the object, that is, the point where we customize this
Call and apply are the two ways
Function.prototype.call ()
//function.prototype.apply ()
//--> any function can invoke call and apply methods
// The first parameter controls the point of this, the second argument:
when a context call is used, the original function (method) may have parameters, and then the argument uses the second (nth) argument in the context call to represent the
Pseudo Array
var o={0:10,1:20,length:2};
Let the O object borrow the push method of the array to add the element
//[].push.call (o,30,50,70)
[].push.apply (o,[1,2,3])
console.log (o); The value of the Length property in object o also changes.
Thank you for reading, I hope to help you, thank you for your support for this site!