深入挖掘js之函数
前言: 前端这两年的新技术铺天盖地,各种框架、工具层出不穷眼花缭乱。最近打算好好复习下 js 基础,夯实的基础才是学习新技术的基石。本文作为读书笔记简单的总结下 js 函数的基础知识。 一、函数对象
二、函数字面量函数对象通过函数字面量来创建: var add = function(a,b){ 函数字面量包括四个部分:
注意:一个内部函数除了可以访问自己的参数和变量,同时也可以自由的访问父函数的参数和变量。用过这种函数字面量创建的函数对象包含一个连接到外部上下文的连接。这个被称为闭包 三、函数调用
方法调用模式当有个函数被保存为对象的一个属性是,我们称他为一个方法。当以个方法被调用时,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()); Apply 调用模式
var array = [3,4]; var statusObject = { status: 'A-ok' }; var status = Quo.prototype.get_status.apply(statusObject); console.log(status); //A-OK 参数
arguments并不是一个真正的数组,拥有一个length属性,但它没有任何数组的方法 返回
四、函数作用域
var a = 2; 闭包
var que = function(status){ return { get_status: function(){ return status; } } } var myQuo = que("hello"); console.log(myQuo.get_status()); get_status方法并不是访问参数的副本,他访问的就是参数的本身,这就是闭包,保护status为私有属性 回调callBack()
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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |