javascript函数(续)

3 篇文章 0 订阅
1 篇文章 0 订阅

javascript函数(续)

以函数为参数

​ 函数本身是一个对象,因此可以将函数作为另一个函数的参数,进而实现函数回调,功能等同于c++中的函数指针

function printf(str){

​ dom1.innerText += str.toString()+"\n"; //设置dom1显示的文字。变量也可以自动调用其他js文件中的dom1变量。dom1会先在当前文件中查询,然后向之前引用的js文件查询,再向之后引用的js文件查询

function callfunction(myfunction,myargument){           //函数作为其他函数的参数

​    return myfunction(myargument);                      //调用回调函数

}

callfunction(printf,"hello world");

同步

当形参与实参的个数相同时,arguments对象的值和对应形参的值保持同步

function test(num1,num2){

​    console.log(num1,arguments[0]);//1 1

​    arguments[0] = 2;

​    console.log(num1,arguments[0]);//2 2

​    num1 = 10;

​    console.log(num1,arguments[0]);//10 10

}

test(1);

[注意]虽然命名参数和对应arguments对象的值相同,但并不是相同的命名空间。它们的命名空间是独立的,但值是同步的

但在严格模式下,arguments对象的值和形参的值是独立的

function test(num1,num2){

​    'use strict';

​    console.log(num1,arguments[0]);//1 1

​    arguments[0] = 2;

​    console.log(num1,arguments[0]);//1 2

​    num1 = 10;

​    console.log(num1,arguments[0]);//10 2

}

test(1);

​ 当形参并没有对应的实参时,arguments对象的值与形参的值并不对应

function test(num1,num2){

​    console.log(num1,arguments[0]);//undefined,undefined

​    num1 = 10;

​    arguments[0] = 5;

​    console.log(num1,arguments[0]);//10,5

}

test();

内部属性【callee】

arguments对象有一个名为callee的属性,该属性是一个指针,指向拥有这个arguments对象的函数

js中函数阶乘问题
var factorial = function fn(num){

​    if(num <=1){

​        return 1;

​    }else{

​        return num*fn(num-1);

​    }

};    

console.log(factorial(5));//120

【caller】

实际上有两个caller属性

【1】函数的caller

函数的caller属性保存着调用当前函数的函数的引用,如果是在全局作用域中调用当前函数,它的值是null

function outer(){

​    inner();

}function inner(){

​    console.log(inner.caller);//outer(){inner();}}

outer();

function inner(){

​    console.log(inner.caller);//null}

inner();

​ 在严格模式下,访问这个属性会抛出TypeError错误

function inner(){

​ ‘use strict’;

​ //TypeError: ‘caller’ and ‘arguments’ are restricted function properties and cannot be accessed in this context console.log(inner.caller);

}

inner();

【2】arguments对象的caller

该属性始终是undefined,定义这个属性是为了分清arguments.caller和函数的caller属性

function inner(x){

​ console.log(arguments.caller);//undefined}

inner(1);

​ 同样地,在严格模式下,访问这个属性会抛出TypeError错误

function inner(x){

​ ‘use strict’;

​ //TypeError: ‘caller’ and ‘arguments’ are restricted function properties and cannot be accessed in this context console.log(arguments.caller);

}

inner(1);

函数重载

javascript函数不能像传统意义上那样实现重载。而在其他语言中,可以为一个函数编写两个定义,只要这两个定义的签名(接受的参数的类型和数量)不同即可

javascript函数没有签名,因为其参数是由包含0或多个值的数组来表示的。而没有函数签名,真正的重载是不可能做到的

//后面的声明覆盖了前面的声明function addSomeNumber(num){

    return num + 100;

}function addSomeNumber(num){

​    return num + 200;

}

var result = addSomeNumber(100);//300

​ 只能通过检查传入函数中参数的类型和数量并作出不同的反应,来模仿方法的重载

function doAdd(){

​    if(arguments.length == 1){

​        alert(arguments[0] + 10);

​    }else if(arguments.length == 2){

​        alert(arguments[0] + arguments[1]);

​    }

}

doAdd(10);//20

doAdd(30,20);//50
参数传递

javascript中所有函数的参数都是按值传递的。也就是说,把函数外部的值复制到函数内部的参数,就和把值从一个变量复制到另一个变量一样

【1】基本类型值

在向参数传递基本类型的值时,被传递的值会被复制给一个局部变量(命名参数或arguments对象的一个元素)

function addTen(num){

​    num += 10;

​    return num;

}

var count = 20;var result = addTen(count);

console.log(count);//20,没有变化

console.log(result);//30

【2】引用类型值

在向参数传递引用类型的值时,会把这个值在内存中的地址复制给一个局部变量,因此这个局部变量的变化会反映在函数的外部

function setName(obj){

​    obj.name = 'test';

}var person = new Object();

setName(person);

console.log(person.name);//'test'

​ 当在函数内部重写引用类型的形参时,这个变量引用的就是一个局部对象了。而这个局部对象会在函数执行完毕后立即被销毁

function setName(obj){

​    obj.name = 'test';

​    console.log(person.name);//'test'

​    obj = new Object();

​    obj.name = 'white';

​    console.log(person.name);//'test'}var person = new Object();

setName(person);

函数属性

【length属性】

arguments对象的length属性表示实参个数,而函数的length属性则表示形参个数

function add(x,y){

​    console.log(arguments.length)//3

​    console.log(add.length);//2}

add(1,2,3);

【name属性】

函数定义了一个非标准的name属性,通过这个属性可以访问到给定函数指定的名字,这个属性的值永远等于跟在function关键字后面的标识符,匿名函数的name属性为空

//IE11-浏览器无效,均输出undefined

//chrome在处理匿名函数的name属性时有问题,会显示函数表达式的名字function fn(){};

console.log(fn.name);//'fn’var fn = function(){};

console.log(fn.name);//’’,在chrome浏览器中会显示’fn’var fn = function abc(){};

console.log(fn.name);//‘abc’

[注意]name属性早就被浏览器广泛支持,但是直到ES6才将其写入了标准

ES6对这个属性的行为做出了一些修改。如果将一个匿名函数赋值给一个变量,ES5的name属性,会返回空字符串,而ES6的name属性会返回实际的函数名

var func1 = function () {};

func1.name //ES5: “”

func1.name //ES6: “func1”

​ 如果将一个具名函数赋值给一个变量,则ES5和ES6的name属性都返回这个具名函数原本的名字

var bar = function baz() {};

bar.name //ES5: “baz”

bar.name //ES6: “baz”

​ Function构造函数返回的函数实例,name属性的值为“anonymous”

bind返回的函数,name属性值会加上“bound ”前缀

【prototype属性】

每一个函数都有一个prototype属性,这个属性指向一个对象的引用,这个对象称做原型对象(prototype object)。每一个函数都包含不同的原型对象。将函数用做构造函数时,新创建的对象会从原型对象上继承属性

函数方法

【apply()和call()】

每个函数都包含两个非继承而来的方法:apply()和call()。这两个方法的用途都是在特定的作用域中调用函数,实际上等于函数体内this对象的值

要想以对象o的方法来调用函数f(),可以这样使用call()和apply()

假设o中不存在m方法,则等价于:

下面是一个实际的例子

window.color = "red";var o = {color: "blue"};function sayColor(){

​    console.log(this.color);

}

sayColor();            //red

sayColor.call(this);   //red

sayColor.call(window); //red

sayColor.call(o);      //blue

//sayColor.call(o)等价于:

o.sayColor = sayColor;

o.sayColor();   //bluedelete o.sayColor;

​ apply()方法接收两个参数:一个是在其中运行函数的作用域(或者可以说成是要调用函数的母对象,它是调用上下文,在函数体内通过this来获得对它的引用),另一个是参数数组。其中,第二个参数可以是Array的实例,也可以是arguments对象

function sum(num1, num2){

​ return num1 + num2;

}//因为运行函数的作用域是全局作用域,所以this代表的是window对象function callSum1(num1, num2){

​ return sum.apply(this, arguments);

}function callSum2(num1, num2){

​ return sum.apply(this, [num1, num2]);

}

console.log(callSum1(10,10));//20

console.log(callSum2(10,10));//20

​ call()方法与apply()方法的作用相同,它们的区别仅仅在于接收参数的方式不同。对于call()方法而言,第一个参数是this值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用call()方法时,传递给函数的参数必须逐个列举出来

function sum(num1,   num2)
{return num1 + num2;}
function callSum(num1,   num2)
{ 
return sum.call( this num1,num2);
}
console.log(callSum(10,10));//20

至于是使用apply()还是call(),完全取决于采取哪种函数传递参数的方式最方便。如果打算直接传入arguments对象,或者包含函数中先接收到的也是一个数组,那么使用apply()肯定更方便;否则,选择call()可能更合适

在非严格模式下,使用函数的call()或apply()方法时,null或undefined值会被转换为全局对象。而在严格模式下,函数的this值始终是指定的值

应用

【1】调用对象的原生方法

var obj = {};

obj.hasOwnProperty(‘toString’);// false

obj.hasOwnProperty = function (){

return true;

};

obj.hasOwnProperty(‘toString’);// true

Object.prototype.hasOwnProperty.call(obj, ‘toString’);// false

【2】找出数组最大元素

javascript不提供找出数组最大元素的函数。结合使用apply方法和Math.max方法,就可以返回数组的最大元素

var a = [10, 2, 4, 15, 9];

Math.max.apply(null, a);//15

【3】将类数组对象转换成真正的数组

Array.prototype.slice.apply({0:1,length:1});//[1] 或者

[].prototype.slice.apply({0:1,length:1});//[1]

【4】将一个数组的值push到另一个数组中

var a = [];

Array.prototype.push.apply(a,[1,2,3]);

console.log(a);//[1,2,3]

Array.prototype.push.apply(a,[2,3,4]);

console.log(a);//[1,2,3,2,3,4]

【5】绑定回调函数的对象

由于apply方法(或者call方法)不仅绑定函数执行时所在的对象,还会立即执行函数,因此不得不把绑定语句写在一个函数体内。更简洁的写法是采用下面介绍的bind方法

var o = {};

o.f = function () {

console.log(this === o);

}var f = function (){

o.f.apply(o);

};

$(’#button’).on(‘click’, f);

【bind()】

bind()是ES5新增的方法,这个方法的主要作用就是将函数绑定到某个对象

当在函数f()上调用bind()方法并传入一个对象o作为参数,这个方法将返回一个新的函数。以函数调用的方式调用新的函数将会把原始的函数f()当做o的方法来调用,传入新函数的任何实参都将传入原始函数

[注意]IE8-浏览器不支持

function f(y){

​ return this.x + y; //这个是待绑定的函数}var o = {x:1};//将要绑定的对象var g = f.bind(o); //通过调用g(x)来调用o.f(x)

g(2);//3

兼容代码

function bind(f,o){

​ if(f.bind){

​ return f.bind(o);

​ }else{

​ return function(){

​ return f.apply(o,arguments);

​ }

​ }

}

​ bind()方法不仅是将函数绑定到一个对象,它还附带一些其他应用:除了第一个实参之外,传入bind()的实参也会绑定到this,这个附带的应用是一种常见的函数式编程技术,有时也被称为’柯里化’(currying)

var sum = function(x,y){

​ return x+y;

}var succ = sum.bind(null,1);

succ(2); //3,x绑定到1,并传入2作为实参yfunction f(y,z){

​ return this.x + y + z;

}var g = f.bind({x:1},2);

g(3); //6,this.x绑定到1,y绑定到2,z绑定到3

使用bind()方法实现柯里化可以对函数参数进行拆分

function getConfig(colors,size,otherOptions){

​ console.log(colors,size,otherOptions);

}var defaultConfig = getConfig.bind(null,’#c00’,‘1024*768’);

defaultConfig(‘123’);//’#c00 1024*768 123’

defaultConfig(‘456’);//’#c00 1024*768 456’

【toString()】

函数的toString()实例方法返回函数代码的字符串,而静态toString()方法返回一个类似’[native code]’的字符串作为函数体

function test(){

​ alert(1);//test}

test.toString();/*"function test(){

​ alert(1);//test

​ }"*/

Function.toString();//“function Function() { [native code] }”

【toLocaleString()】

函数的toLocaleString()方法和toString()方法返回的结果相同

function test(){

​ alert(1);//test}

test.toLocaleString();/*"function test(){

​ alert(1);//test

​ }"*/

Function.toLocaleString();//“function Function() { [native code] }”

【valueOf()】

函数的valueOf()方法返回函数本身

function test(){

​ alert(1);//test}

test.valueOf();/*function test(){

​ alert(1);//test

​ }*/typeof test.valueOf();//‘function’

Function.valueOf();//Function() { [native code] }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值