函数调用
js函数调用有4种形式:
方法调用、正常函数调用、构造器函数调用、apply/call调用
注意:函数调用时参数包括声明时定义的形参及自动添加的两个形参this和arguments.
1、this指向
1.1、方法调用
var oldObj = { init:function(opt){ this.opt=opt; }, create:function(obj){ this.opt.push(obj); }, add:function(obj){ this.create(obj); } }
对于add方法来说,作为oldObj对象的一个属性,this指向此对象oldObj.
1.2、正常函数调用
function f(score){ this.score = score; } f(5);
此时this指向全局对象及window对象.
1.3、构造器函数调用
function oldF (opt){ this.opt=opt; } var newF = new oldF(5);
this指向通过构造器新产生的对象newF.为了保证与正常函数调用的区别,构造器函数调用一般在new后第一个字母大写,改写如下:
function OldF (opt){ this.opt=opt; } var newF = new OldF(5);
1.4、apply/call调用
var oldObj = { init:function(opt){ this.opt=opt; }, create:function(obj){ this.opt.push(obj); }, add:function(obj){ this.create(obj); } }; var newObj = { delete:function(obj){ this.opt.pop(obj); } } oldObj.init.call(newObj,[5]);
this指向newObj.基于apply/call调用可用来改变this指向,本例通过oldObj的方法来操作newObj.
2、命名空间
(function(){ this.scoreArr = new Array(); this.add = function(opt){ this.scoreArr.push(opt); } }).call(someObj); someObj.add(5);
通过(function(){}).call(someObj),函数里的this指向someObj,函数的实现相当于对someObj对象的改造或者someObj对象的实现.
主要作用是隔离上下文,避免变量冲突.