js 函数

来源于一个回答:http://segmentfault.com/q/1010000002519489

js函数调用模式:方法,正常函数,构造器,apply/call

无论哪种函数调用除了你声明时定义的形参外,还会自动添加2个形参,分别是 this 和 arguments。

四种调用模式下,this会指向不同的值。

方法

var a = {
    v : 0,
    f : function(xx) {
        this.v = xx;
    }
}
a.f(5);

this指向a

正常函数

function f(xx) {
    this.x = xx;
}
f(5);

this指向window,如果 window 没有 x 属性,那么你这么一写,就是给 window 对象添加了一个 x 属性,同时赋值。

构造器函数

function a(xx) {
    this.m = xx;
}
var b = new a(5);

this 绑定的就不再是前面讲到的全局对象了,而是这里说的创建的新对象b

apply/call

function a(xx) {
    this.b = xx;
}
var o = {};
a.apply(o, [5]);//调用a,o作为a中的this,[5]是传给a的参数
alert(a.b);    // undefined
alert(o.b);    // 5

严格模式下,访问的变量必须显示声明。  

  

原文地址:https://www.cnblogs.com/wang-jing/p/4731514.html