Home > Web Front-end > JS Tutorial > Four calling modes of Javascript functions

Four calling modes of Javascript functions

黄舟
Release: 2016-12-13 16:41:30
Original
1148 people have browsed it

Four calling modes of Javascript functions

1 Function mode

The most common function call

// 声明式函数 
function fn1 () {    
console.log(this); 
} 
// 函数表达式函数 
var fn2 = function() {    
console.log(this); 
}; 
// 调用 函数中this表示全局对象,在浏览器中就是指window 
fn1();   //window 
fn2();   //window
Copy after login

2 Method mode

A function is attached to an object and is an attribute of the object. We then call this function. This pattern is the method calling pattern.

var obj = {
  name: "zhangSan",
  sayHi: function () {
    console.log(this);
  }
};
obj.sayHi(); //obj对象
Copy after login

3 Constructor calling mode

is the calling of the constructor, usually through new + function name ( ). This mode is not essentially different from the above method mode

function Person() {}
var tom = new Person(); // 这就是构造器函数的调用 
  
// 构造函数调用的详细过程
// 1 会在内部创建一个对象o
// 2 给对象赋值(this), 然后执行各种操作
// 3 返回这个对象o

// 构造函数的返回值:
 //
 //  有一个默认的返回值,新创建的对象(实例);
 //  当手动添加返回值后(return语句):
 //     1. 返回值是基本数据类型-->真正的返回值还是那个新创建的对象(即实例)
 //    2. 返回值是复杂数据类型(对象)-->真正的返回值是这个对象
Copy after login

4 Context mode

The essence - the object borrows a method (function) that does not belong to the object, that is, we customize the point of this

At this time, we need the two methods call and apply

//Function.prototype.call ()
  //Function.prototype.apply ()
  //——>任何函数都可以调用call和apply方法
  
  // 第一个参数控制this的指向,第二个参数:
        在使用 上下文调用的 时候, 原函数(方法)可能会带有参数, 那么这个参数在上下文调用中使用 第二个( 第 n 个 )参数来表示
Copy after login
//伪数组
  var o={ 0:10,1:20,length:2 };
  
  //让o对象借用数组的push方法来添加元素
  //[].push.call(o,30,50,70)
  [].push.apply(o,[1,2,3])
  console.log(o);//其中对象o中length属性的值也会改变的哦
Copy after login

Thanks for reading, I hope it can help everyone , for more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template