web魔集大前端前端杂货铺

JavaScript里的函数调用

2016-11-25  本文已影响57人  前端搬砖工曹果

一.函数调用形式:

function fun(){

alert ("123");

fun( );

var fun =function (){

alert ("123");

}

fun( );

函数调用也称一般调用,在函数调用模式中,this关键字指的是全局对象,如果在浏览器中就是指的是window。

二.方法调用:

var fun=function(){

alert("1234");

};

var a={};

a.fn=fun;

a.fn();

var func=function(){

console.log(this);

};

var o={};

o.fn=func;

func(); //"[object Window]"

o.fn(); //"[object Object]"

console.log(o.fn===func);//true

这时调用的是对象a上面的方法fn,函数调用和方法调用的区别就是this关键字的指向,函数调用this指的是全局对象,方法调用中的this指的是当前对象。

三.构造器调用:

var Person=function(){

this.name = ' 英雄联盟 ' ;  //此时的this是window

this.say = function(){

console.log ( "欢迎来到"+this.name );

};

};

var p=new Person() ; //new创建一个p对象

p.say(); //当p调用say方法时,this就是p对象。

在构造函数中this指的是被创建的对象。

1.所有需要有对象使用的属性,必须使用this引导。

var Person=function(){

this.name='英雄联盟';

return {

name:'data'

}

};

var p=new Person();

console.log(p.name);//data

var Person=function(){

this.name='英雄联盟';

return 'data';

};

var p=new Person();

console.log(p);//"[object Object]"

console.log(p.name);          //'英雄联盟'

2.函数的return语句意义被改写,如果返回的是原意,那么保留return的意义,返回return后面的对象,如果返回非对象(字符串,数值,布尔等),就返回this,不指定return返回的也是this。

四.apply调用模式:

var Person=function(){

this.name='英雄联盟';

console.log(this); // "[object Window]"

};

Person.apply(null);    //使用了null

console.log(name);

var Person2=function(){

this.name='英雄联盟';

console.log(this); //"[object Object]"

};

var o={} ;           //使用了对象

Person2.apply(o);

console.log(o.name);

函数作为对象还有apply方法和call方法使用。

apply和call的区别就是apply中的参数是数组。

使用call和apply模式可以任意操作this的意义,在这个模式中如果使用了null,就是函数模式,如果使用了对象,就是方法模式。

上一篇 下一篇

猜你喜欢

热点阅读