所有函數(shù)都有返回值,沒(méi)有return語(yǔ)句時(shí),默認(rèn)返回內(nèi)容為undefined,和其他面向?qū)ο蟮木幊陶Z(yǔ)言一樣,return語(yǔ)句不會(huì)阻止finally子句的執(zhí)行。
function testFinnally(){ try{ return 2; }catch(error){ return 1; }finally{ return 0; }}testFinnally();//0
如果函數(shù)調(diào)用時(shí)在前面加上了new前綴,且返回值不是一個(gè)對(duì)象,則返回this(該新對(duì)象)。
function fn(){ this.a = 2; return 1;}var test = new fn();console.log(test);//{a:2}console.log(test.constructor);//fn(){this.a = 2;return 1;}
如果返回值是一個(gè)對(duì)象,則返回該對(duì)象。
function fn(){ this.a = 2; return {a:1};}var test = new fn();console.log(test);//{a:1}console.log(test.constructor);//Object() { [native code] }
arguments
javascript中的函數(shù)定義并未指定函數(shù)形參的類(lèi)型,函數(shù)調(diào)用也未對(duì)傳入的實(shí)參值做任何類(lèi)型檢查。實(shí)際上,javascript函數(shù)調(diào)用甚至不檢查傳入形參的個(gè)數(shù)。
1 2 3 4 5 6 7 | function add(x){ return x+1; } console.log(add(1)); //2 console.log(add( '1' )); //'11' console.log(add()); //NaN console.log(add(1,2)); //2 |
同名形參
在非嚴(yán)格模式下,函數(shù)中可以出現(xiàn)同名形參,且只能訪問(wèn)最后出現(xiàn)的該名稱(chēng)的形參。
function add(x,x,x){ return x;}console.log(add(1,2,3));//3
而在嚴(yán)格模式下,出現(xiàn)同名形參會(huì)拋出語(yǔ)法錯(cuò)誤
function add(x,x,x){ 'use strict'; return x;}console.log(add(1,2,3));//SyntaxError: Duplicate parameter name not allowed in this context
參數(shù)個(gè)數(shù)
當(dāng)實(shí)參比函數(shù)聲明指定的形參個(gè)數(shù)要少,剩下的形參都將設(shè)置為undefined值
function add(x,y){ console.log(x,y);//1 undefined}add(1);
常常使用邏輯或運(yùn)算符給省略的參數(shù)設(shè)置一個(gè)合理的默認(rèn)值
function add(x,y){ y = y || 2; console.log(x,y);//1 2}add(1);
[注意]實(shí)際上,使用y || 2是不嚴(yán)謹(jǐn)?shù)?,顯式地設(shè)置假值(undefined、null、false、0、-0、”、NaN)也會(huì)得到相同的結(jié)果。所以應(yīng)該根據(jù)實(shí)際場(chǎng)景進(jìn)行合理設(shè)置
當(dāng)實(shí)參比形參個(gè)數(shù)要多時(shí),剩下的實(shí)參沒(méi)有辦法直接獲得,需要使用即將提到的arguments對(duì)象
javascript中的參數(shù)在內(nèi)部用一個(gè)數(shù)組表示。函數(shù)接收到的始終都是這個(gè)數(shù)組,而不關(guān)心數(shù)組中包含哪些參數(shù)。在函數(shù)體內(nèi)可以通過(guò)arguments對(duì)象來(lái)訪問(wèn)這個(gè)參數(shù)數(shù)組,從而獲取傳遞給函數(shù)的每一個(gè)參數(shù)。arguments對(duì)象并不是Array的實(shí)例,它是一個(gè)類(lèi)數(shù)組對(duì)象,可以使用方括號(hào)語(yǔ)法訪問(wèn)它的每一個(gè)元素
function add(x){ console.log(arguments[0],arguments[1],arguments[2])//1 2 3 return x+1;}add(1,2,3);
arguments對(duì)象的length屬性顯示實(shí)參的個(gè)數(shù),函數(shù)的length屬性顯示形參的個(gè)數(shù)
function add(x,y){ console.log(arguments.length)//3 return x+1;}add(1,2,3);console.log(add.length);//2
形參只是提供便利,但不是必需的
function add(){ return arguments[0] + arguments[1];}console.log(add(1,2));//3
對(duì)象參數(shù)
當(dāng)一個(gè)函數(shù)包含超過(guò)3個(gè)形參時(shí),要記住調(diào)用函數(shù)中實(shí)參的正確順序?qū)嵲谧屓祟^疼
function arraycopy(/*array*/from,/*index*/form_start,/*array*/to,/*index*/to_start,/*integer*/length){ //todo}
通過(guò)名/值對(duì)的形式來(lái)傳入?yún)?shù),這樣參數(shù)的順序就無(wú)關(guān)緊要了。定義函數(shù)的時(shí)候,傳入的實(shí)參都寫(xiě)入一個(gè)單獨(dú)的對(duì)象之中,在調(diào)用的時(shí)候傳入一個(gè)對(duì)象,對(duì)象中的名/值對(duì)是真正需要的實(shí)參數(shù)據(jù)
function easycopy(args){ arraycopy(args.from,args.from_start || 0,args.to,args.to_start || 0, args.length);}var a = [1,2,3,4],b =[];easycopy({from:a,to:b,length:4});
以函數(shù)為參數(shù)
函數(shù)本身是一個(gè)對(duì)象,因此可以將函數(shù)作為另一個(gè)函數(shù)的參數(shù),進(jìn)而實(shí)現(xiàn)函數(shù)回調(diào),功能等同于c++中的函數(shù)指針
function printf(str){ dom1.innerText += str.toString()+"\n"; //設(shè)置dom1顯示的文字。變量也可以自動(dòng)調(diào)用其他js文件中的dom1變量。dom1會(huì)先在當(dāng)前文件中查詢,然后向之前引用的js文件查詢,再向之后引用的js文件查詢}function callfunction(myfunction,myargument){ //函數(shù)作為其他函數(shù)的參數(shù) return myfunction(myargument); //調(diào)用回調(diào)函數(shù)}callfunction(printf,"hello world");
同步
當(dāng)形參與實(shí)參的個(gè)數(shù)相同時(shí),arguments對(duì)象的值和對(duì)應(yīng)形參的值保持同步
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);
[注意]雖然命名參數(shù)和對(duì)應(yīng)arguments對(duì)象的值相同,但并不是相同的命名空間。它們的命名空間是獨(dú)立的,但值是同步的
但在嚴(yán)格模式下,arguments對(duì)象的值和形參的值是獨(dú)立的
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);
當(dāng)形參并沒(méi)有對(duì)應(yīng)的實(shí)參時(shí),arguments對(duì)象的值與形參的值并不對(duì)應(yīng)
function test(num1,num2){ console.log(num1,arguments[0]);//undefined,undefined num1 = 10; arguments[0] = 5; console.log(num1,arguments[0]);//10,5}test();
內(nèi)部屬性【callee】
arguments對(duì)象有一個(gè)名為callee的屬性,該屬性是一個(gè)指針,指向擁有這個(gè)arguments對(duì)象的函數(shù)
下面是經(jīng)典的階乘函數(shù)
function factorial(num){ if(num <=1){ return 1; }else{ return num* factorial(num-1); }} console.log(factorial(5));//120
但在嚴(yán)格模式下,訪問(wèn)這個(gè)屬性會(huì)拋出TypeError錯(cuò)誤
function factorial(num){ 'use strict'; if(num <=1){ return 1; }else{ return num* arguments.callee(num-1); }} //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to themconsole.log(factorial(5));
這時(shí),可以使用具名的函數(shù)表達(dá)式
var factorial = function fn(num){ if(num <=1){ return 1; }else{ return num*fn(num-1); }}; console.log(factorial(5));//120
【caller】
實(shí)際上有兩個(gè)caller屬性
【1】函數(shù)的caller
函數(shù)的caller屬性保存著調(diào)用當(dāng)前函數(shù)的函數(shù)的引用,如果是在全局作用域中調(diào)用當(dāng)前函數(shù),它的值是null
function inner(){ console.log(inner.caller);//null}inner();
在嚴(yán)格模式下,訪問(wèn)這個(gè)屬性會(huì)拋出TypeError錯(cuò)誤
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對(duì)象的caller
該屬性始終是undefined,定義這個(gè)屬性是為了分清arguments.caller和函數(shù)的caller屬性
function inner(x){ console.log(arguments.caller);//undefined}inner(1);
同樣地,在嚴(yán)格模式下,訪問(wèn)這個(gè)屬性會(huì)拋出TypeError錯(cuò)誤
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);
函數(shù)重載
javascript函數(shù)不能像傳統(tǒng)意義上那樣實(shí)現(xiàn)重載。而在其他語(yǔ)言中,可以為一個(gè)函數(shù)編寫(xiě)兩個(gè)定義,只要這兩個(gè)定義的簽名(接受的參數(shù)的類(lèi)型和數(shù)量)不同即可
javascript函數(shù)沒(méi)有簽名,因?yàn)槠鋮?shù)是由包含0或多個(gè)值的數(shù)組來(lái)表示的。而沒(méi)有函數(shù)簽名,真正的重載是不可能做到的
//后面的聲明覆蓋了前面的聲明function addSomeNumber(num){ return num + 100;}function addSomeNumber(num){ return num + 200;}var result = addSomeNumber(100);//300
只能通過(guò)檢查傳入函數(shù)中參數(shù)的類(lèi)型和數(shù)量并作出不同的反應(yīng),來(lái)模仿方法的重載
function doAdd(){ if(arguments.length == 1){ alert(arguments[0] + 10); }else if(arguments.length == 2){ alert(arguments[0] + arguments[1]); }}doAdd(10);//20doAdd(30,20);//50
參數(shù)傳遞
javascript中所有函數(shù)的參數(shù)都是按值傳遞的。也就是說(shuō),把函數(shù)外部的值復(fù)制到函數(shù)內(nèi)部的參數(shù),就和把值從一個(gè)變量復(fù)制到另一個(gè)變量一樣
【1】基本類(lèi)型值
在向參數(shù)傳遞基本類(lèi)型的值時(shí),被傳遞的值會(huì)被復(fù)制給一個(gè)局部變量(命名參數(shù)或arguments對(duì)象的一個(gè)元素)
function addTen(num){ num += 10; return num;}var count = 20;var result = addTen(count);console.log(count);//20,沒(méi)有變化console.log(result);//30
【2】引用類(lèi)型值
在向參數(shù)傳遞引用類(lèi)型的值時(shí),會(huì)把這個(gè)值在內(nèi)存中的地址復(fù)制給一個(gè)局部變量,因此這個(gè)局部變量的變化會(huì)反映在函數(shù)的外部
function setName(obj){ obj.name = 'test';}var person = new Object();setName(person);console.log(person.name);//'test'
當(dāng)在函數(shù)內(nèi)部重寫(xiě)引用類(lèi)型的形參時(shí),這個(gè)變量引用的就是一個(gè)局部對(duì)象了。而這個(gè)局部對(duì)象會(huì)在函數(shù)執(zhí)行完畢后立即被銷(xiāo)毀
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對(duì)象的length屬性表示實(shí)參個(gè)數(shù),而函數(shù)的length屬性則表示形參個(gè)數(shù)
function add(x,y){ console.log(arguments.length)//3 console.log(add.length);//2}add(1,2,3);
【name屬性】
函數(shù)定義了一個(gè)非標(biāo)準(zhǔn)的name屬性,通過(guò)這個(gè)屬性可以訪問(wèn)到給定函數(shù)指定的名字,這個(gè)屬性的值永遠(yuǎn)等于跟在function關(guān)鍵字后面的標(biāo)識(shí)符,匿名函數(shù)的name屬性為空
//IE11-瀏覽器無(wú)效,均輸出undefined//chrome在處理匿名函數(shù)的name屬性時(shí)有問(wèn)題,會(huì)顯示函數(shù)表達(dá)式的名字function fn(){};console.log(fn.name);//'fn'var fn = function(){};console.log(fn.name);//'',在chrome瀏覽器中會(huì)顯示'fn'var fn = function abc(){};console.log(fn.name);//'abc'
[注意]name屬性早就被瀏覽器廣泛支持,但是直到ES6才將其寫(xiě)入了標(biāo)準(zhǔn)
ES6對(duì)這個(gè)屬性的行為做出了一些修改。如果將一個(gè)匿名函數(shù)賦值給一個(gè)變量,ES5的name屬性,會(huì)返回空字符串,而ES6的name屬性會(huì)返回實(shí)際的函數(shù)名
var func1 = function () {};func1.name //ES5: ""func1.name //ES6: "func1"
如果將一個(gè)具名函數(shù)賦值給一個(gè)變量,則ES5和ES6的name屬性都返回這個(gè)具名函數(shù)原本的名字
var bar = function baz() {};bar.name //ES5: "baz"bar.name //ES6: "baz"
Function構(gòu)造函數(shù)返回的函數(shù)實(shí)例,name屬性的值為“anonymous”
1 | ( new Function).name // "anonymous" |
bind返回的函數(shù),name屬性值會(huì)加上“bound ”前綴
1 2 3 | function foo() {}; foo.bind({}).name // "bound foo" ( function (){}).bind({}).name // "bound " |
【prototype屬性】
每一個(gè)函數(shù)都有一個(gè)prototype屬性,這個(gè)屬性指向一個(gè)對(duì)象的引用,這個(gè)對(duì)象稱(chēng)做原型對(duì)象(prototype object)。每一個(gè)函數(shù)都包含不同的原型對(duì)象。將函數(shù)用做構(gòu)造函數(shù)時(shí),新創(chuàng)建的對(duì)象會(huì)從原型對(duì)象上繼承屬性
1 2 3 4 | function fn(){}; var obj = new fn; fn.prototype.a = 1; console.log(obj.a); //1 |
【apply()和call()】
每個(gè)函數(shù)都包含兩個(gè)非繼承而來(lái)的方法:apply()和call()。這兩個(gè)方法的用途都是在特定的作用域中調(diào)用函數(shù),實(shí)際上等于函數(shù)體內(nèi)this對(duì)象的值
要想以對(duì)象o的方法來(lái)調(diào)用函數(shù)f(),可以這樣使用call()和apply()
1 2 | f.call(o); f.apply(o); |
假設(shè)o中不存在m方法,則等價(jià)于:
1 2 3 | o.m = f; //將f存儲(chǔ)為o的臨時(shí)方法 o.m(); //調(diào)用它,不傳入?yún)?shù) delete o.m; //將臨時(shí)方法刪除 |
下面是一個(gè)實(shí)際的例子
window.color = "red";var o = {color: "blue"};function sayColor(){ console.log(this.color);}sayColor(); //redsayColor.call(this); //redsayColor.call(window); //redsayColor.call(o); //blue
//sayColor.call(o)等價(jià)于:o.sayColor = sayColor;o.sayColor(); //bluedelete o.sayColor;
apply()方法接收兩個(gè)參數(shù):一個(gè)是在其中運(yùn)行函數(shù)的作用域(或者可以說(shuō)成是要調(diào)用函數(shù)的母對(duì)象,它是調(diào)用上下文,在函數(shù)體內(nèi)通過(guò)this來(lái)獲得對(duì)它的引用),另一個(gè)是參數(shù)數(shù)組。其中,第二個(gè)參數(shù)可以是Array的實(shí)例,也可以是arguments對(duì)象
function sum(num1, num2){ return num1 + num2;}//因?yàn)檫\(yùn)行函數(shù)的作用域是全局作用域,所以this代表的是window對(duì)象function callSum1(num1, num2){ return sum.apply(this, arguments);}function callSum2(num1, num2){ return sum.apply(this, [num1, num2]);}console.log(callSum1(10,10));//20console.log(callSum2(10,10));//20
call()方法與apply()方法的作用相同,它們的區(qū)別僅僅在于接收參數(shù)的方式不同。對(duì)于call()方法而言,第一個(gè)參數(shù)是this值沒(méi)有變化,變化的是其余參數(shù)都直接傳遞給函數(shù)。換句話說(shuō),在使用call()方法時(shí),傳遞給函數(shù)的參數(shù)必須逐個(gè)列舉出來(lái)
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(),完全取決于采取哪種函數(shù)傳遞參數(shù)的方式最方便。如果打算直接傳入arguments對(duì)象,或者包含函數(shù)中先接收到的也是一個(gè)數(shù)組,那么使用apply()肯定更方便;否則,選擇call()可能更合適
在非嚴(yán)格模式下,使用函數(shù)的call()或apply()方法時(shí),null或undefined值會(huì)被轉(zhuǎn)換為全局對(duì)象。而在嚴(yán)格模式下,函數(shù)的this值始終是指定的值
1 2 3 4 5 | var color = 'red' ; function displayColor(){ console.log( this .color); } displayColor.call( null ); //red |
1 2 3 4 5 6 | var color = 'red' ; function displayColor(){ 'use strict' ; console.log( this .color); } displayColor.call( null ); //TypeError: Cannot read property 'color' of null |
應(yīng)用
【1】調(diào)用對(duì)象的原生方法
var obj = {};obj.hasOwnProperty('toString');// falseobj.hasOwnProperty = function (){ return true;};obj.hasOwnProperty('toString');// trueObject.prototype.hasOwnProperty.call(obj, 'toString');// false
【2】找出數(shù)組最大元素
javascript不提供找出數(shù)組最大元素的函數(shù)。結(jié)合使用apply方法和Math.max方法,就可以返回?cái)?shù)組的最大元素
var a = [10, 2, 4, 15, 9];Math.max.apply(null, a);//15
【3】將類(lèi)數(shù)組對(duì)象轉(zhuǎn)換成真正的數(shù)組
Array.prototype.slice.apply({0:1,length:1});//[1] 或者[].prototype.slice.apply({0:1,length:1});//[1]
【4】將一個(gè)數(shù)組的值push到另一個(gè)數(shù)組中
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】綁定回調(diào)函數(shù)的對(duì)象
由于apply方法(或者call方法)不僅綁定函數(shù)執(zhí)行時(shí)所在的對(duì)象,還會(huì)立即執(zhí)行函數(shù),因此不得不把綁定語(yǔ)句寫(xiě)在一個(gè)函數(shù)體內(nèi)。更簡(jiǎn)潔的寫(xiě)法是采用下面介紹的bind方法
var o = {};o.f = function () { console.log(this === o);}var f = function (){ o.f.apply(o);};$('#button').on('click', f);
【bind()】
bind()是ES5新增的方法,這個(gè)方法的主要作用就是將函數(shù)綁定到某個(gè)對(duì)象
當(dāng)在函數(shù)f()上調(diào)用bind()方法并傳入一個(gè)對(duì)象o作為參數(shù),這個(gè)方法將返回一個(gè)新的函數(shù)。以函數(shù)調(diào)用的方式調(diào)用新的函數(shù)將會(huì)把原始的函數(shù)f()當(dāng)做o的方法來(lái)調(diào)用,傳入新函數(shù)的任何實(shí)參都將傳入原始函數(shù)
[注意]IE8-瀏覽器不支持
function f(y){ return this.x + y; //這個(gè)是待綁定的函數(shù)}var o = {x:1};//將要綁定的對(duì)象var g = f.bind(o); //通過(guò)調(diào)用g(x)來(lái)調(diào)用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()方法不僅是將函數(shù)綁定到一個(gè)對(duì)象,它還附帶一些其他應(yīng)用:除了第一個(gè)實(shí)參之外,傳入bind()的實(shí)參也會(huì)綁定到this,這個(gè)附帶的應(yīng)用是一種常見(jiàn)的函數(shù)式編程技術(shù),有時(shí)也被稱(chēng)為’柯里化’(currying)
var sum = function(x,y){ return x+y;}var succ = sum.bind(null,1);succ(2); //3,x綁定到1,并傳入2作為實(shí)參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()方法實(shí)現(xiàn)柯里化可以對(duì)函數(shù)參數(shù)進(jìn)行拆分
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()】
函數(shù)的toString()實(shí)例方法返回函數(shù)代碼的字符串,而靜態(tài)toString()方法返回一個(gè)類(lèi)似’[native code]’的字符串作為函數(shù)體
function test(){ alert(1);//test}test.toString();/*"function test(){ alert(1);//test }"*/Function.toString();//"function Function() { [native code] }"
【toLocaleString()】
函數(shù)的toLocaleString()方法和toString()方法返回的結(jié)果相同
function test(){ alert(1);//test}test.toLocaleString();/*"function test(){ alert(1);//test }"*/Function.toLocaleString();//"function Function() { [native code] }"
【valueOf()】
函數(shù)的valueOf()方法返回函數(shù)本身
function test(){ alert(1);//test}test.valueOf();/*function test(){ alert(1);//test }*/typeof test.valueOf();//'function'Function.valueOf();//Function() { [native code] }
原鏈:https://blog.csdn.net/luanpeng825485697/article/details/77010261
聯(lián)系客服