javascript函数调用有以下几种
1.函数调用 :在全局作用域定义函数,并在全局作用域调用
这种情况下的分两种情况,第一:在非严格模式下,this指向window;第二:在严格模式下,this指向undefined
function doSomething(){ return this; } doSomething(); //window function doSomething1(){ "use strict" return this; } doSomething1(); //undefined
2.方法调用 :函数作为某个对象的方法进行调用,此时this指向这个对象
obj={ name:"kk", doSomething:function(){ return this; } } obj.doSomething();
3.构造函数调用 构造函数调用通过添加new关键字来创建,初始化对象。此时构造函数中的this指向这个创建出来的对象。
function Person(){ this.name="kk"; this.doSomething=function(){ return this; } } var person=new Person(); person.doSomething();
4.apply,call调用 这两个方法是函数的方法(函数在js中也是对象),这两个方法都是给函数把某个对象绑定到函数的this上;apply与call方法的第一个参数都是被绑定的对象,后面的参数是函数调用需
要的参数,只是apply接收的参数是以数组的形式传递,而call接收的参数是以参数列表的形式传递
obj={ name:"kk", doSomething:function(){ return this; } } obj1={ name:"aa" }; obj.doSomething.apply(obj1); //{name: "aa"}
5.箭头函数 箭头函数的this指向箭头函数声明的上下文
1 obj={ 2 name:"kk", 3 doSomething:()=>this 4 } 5 obj.doSomething(); 6 //箭头函数在对象字面量中定义,而对象字面量是在全局作用域定义,因此箭头this指向window
原文:https://www.cnblogs.com/lleaky/p/11760920.html