Four Existing Forms of JavaScript Function

  • 2021-06-28 08:31:41
  • OfStack

Four forms of functions exist:

1. Function Form

2. Method morphology assigns a function to a member of an object, which is called a method.

3. Constructor morphology

4. Context Form

1. Functional form:


var foo = function() {
  alert(this);       //this yes window
};

2. Method Form:


o = {};
o.foo = foo;  // Will function foo Assign to Object o Of foo attribute 
o.foo();    // What pops up is object At this time this Express object


var lib = {
  test:function() {
    alert(this);     // Here's the this Express object ( lib Object itself) 
    //var that = this;  // To be in an anonymous function this Express lib Object, you can do this 
    (function() {
     alert(this);    // The anonymous function here does not belong to lib Object, so this Renewable representation of window
    })();
  }
};
lib.test();

3. Constructor (constructor) var p = new Person();

1. new creates objects and opens up space

2. Pass the reference address of the object to the function and receive it in the function with this

3. End of construction method execution, return this


var Person = function() {
  this.age = 19;
  this.name = "Mr Jing ";
  return "{}";
};

var p = new Person();
alert(p.name);  // What pops up is undefined Because the function returns 1 Objects, so return this object directly to person And ignore age , name attribute 

var Person = function() {
  this.age = 19;
  this.name = "Mr Jing ";
  return 123;
};

var p = new Person();
alert(p.name);  *  // Eject" Mr Jing", since the return value is not an object, the return value is ignored directly 
alert(p);      // Eject object

What has changed is that the constructor changes the return value of the function;If the return value of a function is an object, it is returned as the return value.If the return value is not an object, ignore the return value and return this directly.

4. Context call mode function. apply (object, [parameter list])


var foo1 = function(a, b) {
  alert(this);
  return a > b ? a : b;
};
var num = foo1.apply(null, [112, 34]);   // here foo1 Is the function form, this Express window
num = foo1.apply({}, [112, 34]);      // here foo1 Is the method form, this Represents an object passed in from a parameter {}

Function.call (object, parameter list);


var num1 =foo1.call(null,112,34);
num1=foo1.call({},112,34);      // Except for the parameter list, and apply1 kind 

Related articles: