JavaScript学习笔记之函数

一.不同的创建方式:

a.函数声明:

function add(a,b){
    return a+b;
}

b.函数表达式:

var add=function(a,b){
    return a+b;
}

//IEF(Immediately Executed Function)立即执行
(function(a,b){
    return a+b;
})()

//函数对象作为返回值
return function(){
};

//NFE(Named Function Expression) 命名式函数表达式
var add=function foo(a,b){
    return a+b;
}

c.Function构造器

var func=new Function('a','b','console.log(a+b);');
func(2,3);

var func=Function('a','b','console.log(a+b);');
func(2,3);

二.不同的调用方式:

a.直接调用:

foo()

b.对象方法:

o.method()

c.构造器:

new Foo()

d.call/apply/bind:

func.call(o)

三、this:

a.全局的this(浏览器):

console.log(this); //window
console.log(this.document===document); //true

this.a=2;
console.log(window.a); //37

b.一般函数的this(浏览器):

function f1(){
   return this;
}
f1()===windonw; //true

严格模式下,f1()===undefined
c.作为对象方法的函数的this:

var o={
    prop:37,
    f:function(){
        return this.prop;
    }
}
console.log(o.f); //37

var o={prop:37};
function independent(){
    return this.prop
}
o.f=independent;
console.log(o.f()); //37

c.对象原型链上的this:

var o={
    f:function(){
        return this.a+this.b;
    }
};
var p=Object.create(o);
p.a=1;
p.b=4;
console.log(p.f()); //  5

d.构造器中的this:

function MyClass(){
   this.a=37;
}
var o=new MyClass();
console.log(o.a);  //37

function C2(){
   this.a=37;
   return{a:38};
}
o=new C2();
console.log(o.a); //38

在构造器中,没有return语句时,就返回该this,否则返回return的对象

e.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

f.bind方法与this

function f(){
    return this.a;
}
var g=f.bind({a:'test'});
document.write(g());  //test

四、函数属性&arguments:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,657评论 0 5
  • 函数是一块JavaScript代码,被定义一次,但可执行调用多次,js中的函数也是对象,所以js函数可以像其他对象...
    深沉的简单阅读 454评论 0 4
  • 函数只定义一次,但可能被执行或调用任意次。JS函数是参数化的,函数的定义会包括一个称为形参的标识符列表,这些参数在...
    PySong阅读 327评论 0 0
  • 函数只定义一次,但可能被执行或调用任意次。JS函数是参数化的,函数的定义会包括一个称为形参的标识符列表,这些参数在...
    PySong阅读 868评论 0 0
  • 函数只定义一次,但可能被执行或调用任意次。JS函数是参数化的,函数的定义会包括一个称为形参的标识符列表,这些参数在...
    PySong阅读 552评论 0 0