前言: 前端这两年的新技术铺天盖地,各类框架、工具层出不穷眼花缭乱。最近打算好好复习下 js 基础,夯实的基础才是学习新技术的基石。本文做为读书笔记简单的总结下 js 函数的基础知识。前端
函数对象经过函数字面量来建立:数组
var add = function(a,b){
return a+b;
};
函数字面量包括四个部分:闭包
注意:一个内部函数除了能够访问本身的参数和变量,同时也能够自由的访问父函数的参数和变量。用过这种函数字面量建立的函数对象包含一个链接到外部上下文的链接。这个被称为闭包app
当有个函数被保存为对象的一个属性是,咱们称他为一个方法。当以个方法被调用时,this被绑定到该对像。框架
var myObject = { value: 0, increment: function (icn) { this.value += typeof inc === 'number' ? icn: 1; } } myObject.increment(); console.log(myObject.value); myObject.increment(2); console.log(myObject.value);
方法可使用this访问本身所属的对象。经过this可取可取的他们所属对象的上下文的方法称为公共方法异步
myObject.double = function(){ var that = this ; var helper = function(){ that .value = add(that.value,that.value); } helper(); //以函数的形式调用helper } //以方法的形式调用double myObject.double(); console.log(myObject.value);
//建立一个构造器函数Quo var Quo = function(string){ this.status = string; }; //给Quo提供一个get_status的公共方法 Quo.prototype.get_status = function(){ return this.status; }; //构造一个Quo实例 var myQuo = new Quo("hello world"); console.log(myQuo.get_status());
var array = [3,4];
var sum = add.apply(null,array);
var statusObject = { status: 'A-ok' }; var status = Quo.prototype.get_status.apply(statusObject); console.log(status); //A-OK
arguments并非一个真正的数组,拥有一个length属性,但它没有任何数组的方法
var a = 2;
function foo(){
var a =3;
consloe.log(a);//3
}
foo();
consloe.log(a);//2
var que = function(status){ return { get_status: function(){ return status; } } } var myQuo = que("hello"); console.log(myQuo.get_status());
get_status方法并非访问参数的副本,他访问的就是参数的自己,这就是闭包,保护status为私有属性函数
function a(){ console.log('执行a函数'); setTimeout(function(){ console.log("执性a函数的延迟函数") },1000) }; function b (){ console.log('执行函数b') } a(); b();
以上代码会先执行函数a,并且不会等到a中的延迟函数执行完才执行函数b, 在延迟函数被触发的过程当中就执行了函数b,当js引擎的event 队列空闲时才会去执行队列里等待的setTimeout的回调函数,这就是一个异步的例子工具
如下是谷歌得出的结论学习
callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
var foo= (function(){ var something = 'cool'; var another =[1,2,3]; function doSomething(){ console.log(something); } function doAnother(){ console.log(another.join(' ! ')); } return{ doSomething: doSomething, doAnother: doAnother } })(); foo.doSomething(); foo.doAnother();