一、函数调用方法
- 直接调用:foo();
- 对象方法:o.method();
- 构造器:new Foo();
- call/apply/bind:func.call(o);
二、创建函数的方式
- 函数声明
function add(a,b){ //内容 }
- 函数表达式
var add = function(a,b){} //赋值函数表达式 (function(){ })(); //立即执行函数表达式 var add = function foo(a,b){ // 内容 } // 命名式函数表达式
-
两者区别在于变量提升。
Function构造器(函数构造器)
var func = new Function('a','b','console.log(a+b);');
func(1,2); //3
var func = Function('a','b','console.log(a+b);');
func(1,2); //3
//本质上无区别
三、this
- 全局this。
// 浏览器下 console.log(this === window) // true function f1(){ return this; } //浏览器下指向window,node里面指向global function f2() { "use strict"; return this; //严格模式下指向undefined }
-
作为对象方法的函数的this。
var o ={ prop: 37, f: function() { return this.prop; } }; console.log(o.f()); // 37
-
对象原型链上的this。
-
构造器中的this。
function MyClass(){ this.a = 37; } // 正常情况下this指向window var o = new MyClass(){ console.log(o.a); //如果使用new把其作为构造器去调用的话,this会指向一个空的对象,并且这个对像的原型会指向MyClass.prototype,并且this会作为返回值给构造器中。 } function C2(){ this.a =37; return {a:38}; } o = new C2(); console.log(o.a); //38 此时返回的是return的对象,不是this
-
call/apply方法与this。
function add(c,d){ return this.a + this.b + c+d; } var o = {a:1,b:3}; add.call(o,5,7); // 1+3+5+7 = 16 add.apply(o,[10,20]); // 1+3+10+20 = 34 function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); //"[object Number]" //call,apply传参方式不同,call扁平化传入,apply作为数组传入。
-
bind方法。
function f(){ return this.a; } var g = f.bind({a:"test"}); console.log(g()); //test var o = { a:37,f:f,g:g}; console.log(o.f(),o.g()); // 37,test //使用bind绑定之后,this会按照bind的走