JavaScript 中函数的定义和调用

3种函数定义方式:

1、使用关键字 function 来声明并定义函数

function myFunction(a, b) {
    return a * b;
}

调用函数:

var x = myFunction(4, 3);

2、使用关键字 function 来定义匿名函数

function (a, b) {return a * b}

匿名函数可赋值给变量或者自调用。

匿名函数赋值给变量:

var myFunction = function (a, b) {return a * b};

var x = myFunction(4, 3);

匿名函数自调用:

(function (a, b) {
    return a * b;
})(4,3);

3、使用 Function() 构造函数来定义函数

var myFunction = new Function("a", "b", "return a * b");

调用函数:

var x = myFunction(4, 3);

 

注意:

提升(Hoisting)是 JavaScript 默认将当前作用域中的变量声明与函数声明提升到前面去的的行为。

上述3种函数定义方式中第一种方式声明了函数,因此,函数可以在声明之前调用:

myFunction(5);

function myFunction(y) {
    return y * y;
}

 

4 种函数调用方式:

函数调用方式的区别在于调用函数时 this 的初始化不同。

this 是 JavaScript 语言的一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

函数使用的场合不同,this 的值也不同。但是有一个原则:this 代表的是调用函数的那个对象。

1、作为全局函数(全局对象方法)被调用

function myFunction(a, b) {
    return a * b;
}
myFunction(10, 2);           // myFunction(10, 2) 返回 20
window.myFunction(10, 2);    // window.myFunction(10, 2) 返回 20

在 HTML 中默认的全局对象是 HTML 页面本身,所以函数属于 HTML 页面。

在浏览器中的全局对象是浏览器窗口(window 对象),以上函数会自动变为 window 对象的方法。myFunction() 和 window.myFunction() 是一样的。

函数作为全局函数被调用时,this 的值为全局对象。

注意:全局变量、方法或函数容易造成命名冲突的bug,而且使用 window 对象作为一个变量容易造成程序崩溃。

2、作为对象方法被调用

var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
myObject.fullName();         // 返回 "John Doe"

fullName 函数是一个对象方法,属于myObject对象。

函数作为对象方法被调用时,this 的值为它所属的对象。

var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this;
    }
}
myObject.fullName();          // 返回 [object Object] (所有者对象)

3、作为构造函数被调用

在 JavaScript 中,构造函数用于创建新的对象。调用构造函数需要在前面添加 new 关键字。

// 构造函数
function myFunction(arg1, arg2) {
    this.firstName = arg1;
    this.lastName  = arg2;
}
 
// 调用构造函数创建新的对象
var x = new myFunction("John","Doe");
x.firstName;                             // 返回 "John"

新对象会继承构造函数的属性和方法。

构造函数中的 this 关键字没有任何的值。

函数作为构造函数被调用时,this 的值为构造函数所实例化的对象。

4、使用函数方法调用

在 JavaScript 中,函数是对象,函数也有属性和方法。

call()apply() 是预定义的函数方法,我们可以使用这两个方法来调用函数。

function myFunction(a, b) {
    return a * b;
}
var myObject = new Object;
var x = myFunction.call(myObject, 10, 2);     // 返回 20
function myFunction(a, b) {
    return a * b;
}

var myObject = new Object;
var myArray = [10, 2];
var x= myFunction.apply(myObject, myArray);  // 返回 20

call() 和 apply() 两个方法的第一个参数都是对象(函数运行的作用域)。

两者的区别在于第二个参数: apply传入的是一个参数数组或 arguments 对象;而call传入的是一个参数(从第二个参数开始传入参数列表)。

在 JavaScript 严格模式(strict mode)下,使用函数方法调用函数时,第一个参数会成为 this 的值, 即使该参数不是一个对象。

在 JavaScript 非严格模式(non-strict mode)下,如果第一个参数的值是 null 或 undefined, 它将使用全局对象替代。

通过 call() 或 apply() 方法你可以设置 this 的值,且作为已存在对象的新方法调用。

 

参考:http://www.runoob.com/js/js-function-definition.html

100 Responses

  1. Gfpccs说道:

    motilium ca – order tetracycline without prescription buy flexeril generic

  2. Wwenzu说道:

    buy domperidone 10mg generic – where can i buy flexeril order flexeril 15mg generic

  3. Zwobnt说道:

    treat esophagus – buy tenormin no prescription order atenolol 100mg online cheap

  4. Lfbrng说道:

    cenforce price – buy generic cenforce over the counter glycomet 500mg cheap

  5. Klxsxx说道:

    amoxiclav usa – augmentin 625mg uk duloxetine 40mg pills

  6. Lsplek说道:

    buy lasix no prescription – betamethasone 20gm without prescription3 betamethasone uk

  7. Kufoxe说道:

    cheap gabapentin 800mg – buy itraconazole cheap itraconazole uk

  8. Xiekmq说道:

    order omnacortil generic – buy azithromycin online cheap order generic prometrium

  9. Rredfz说道:

    order azithromycin – buy zithromax medication cheap bystolic 5mg

  10. Ppbtez说道:

    amoxil medication – order amoxil generic how to get ipratropium without a prescription

  11. Mclttw说道:

    deltasone 5mg ca – where can i buy starlix order capoten sale

  12. Hddlei说道:

    buy furosemide 100mg without prescription buy furosemide online diuretic ventolin online order

  13. Qzlthe说道:

    buy generic lexapro 20mg purchase naltrexone generic revia tablet

  14. Lgcyaz说道:

    buy strattera 10mg online cheap buy atomoxetine for sale order sertraline online

  15. Wsrues说道:

    azithromycin order online azithromycin 500mg canada buy cheap gabapentin

  16. Ukmjwa说道:

    ursodiol 300mg for sale order cetirizine 5mg generic cetirizine 5mg ca

  17. Kdnmgm说道:

    buy deltasone 20mg order amoxicillin 1000mg online buy generic amoxil 500mg

  18. Warkfv说道:

    omeprazole sandoz capsule 20 mg the best antacids for reflux best medicine for stomach bloating

  19. Bvqlrw说道:

    can you get contraceptive pill from pharmacy nice guidelines enlarged prostate medication for premature ejaculation

  20. Mrfyes说道:

    cymbalta buy online order glucotrol 5mg oral modafinil

  21. Pjaclh说道:

    best supplements for yeast overgrowth best hypertension medication combinations high blood pressure no insurance

  22. Abifrd说道:

    order cyproheptadine 4 mg generic order generic cyproheptadine 4mg nizoral 200mg uk

  23. Iaczui说道:

    valacyclovir how long to take once a week diabetic pill rx for diabetes

  24. Yceeqs说道:

    order provera 5mg medroxyprogesterone pills order microzide 25mg pills

  25. Vmpvon说道:

    is nicobloc fda approved buy pain pills online usa online pain management doctors prescriptions

  26. Rzafhz说道:

    femara 2.5mg without prescription abilify 20mg over the counter order aripiprazole 20mg generic

  27. Qssovo说道:

    buy sleeping meds online can anyone buy sleeping pills buy diet pills online

  28. Pfjvui说道:

    alfuzosin over the counter alphabetical list of allergy medications best non prescription anti nausea

  29. Ovmypb说道:

    buy generic catapres for sale catapres 0.1mg price where to buy tiotropium without a prescription

  30. Hrrbgs说道:

    popular acne prescriptions best cure for teenage acne trileptal uk

  31. Qikmkl说道:

    buy trimox generic buy generic trimox 500mg order clarithromycin generic

  32. Qsgwaf说道:

    order rocaltrol generic buy tricor 200mg without prescription order fenofibrate 200mg sale

  33. Klxzxm说道:

    essay writing assistance owl essay writing cheap suprax

  34. Oqpzkf说道:

    pay for a research paper online casinos online gambling

  35. Cwrxkv说道:

    buy lamisil 250mg online casino no deposit bonus codes

  36. Ysndpy说道:

    aspirin 75mg generic order aspirin for sale luckyland slots

  37. Prwogw说道:

    trazodone for sale trazodone 100mg for sale buy clindac a

  38. Jqgwno说道:

    buy generic tadacip 20mg order generic tadalafil generic indocin

  39. Pjmuvj说道:

    buy retin paypal buy avana sale order avana 100mg sale

  40. Qqktlg说道:

    buy nolvadex pills nolvadex 20mg uk buy generic budesonide online

  41. Sodbru说道:

    buy cleocin 300mg without prescription ed remedies purchase sildenafil pills

  42. Vaafrt说道:

    buy lamictal without prescription minipress 1mg drug purchase vermox for sale

  43. Aalthx说道:

    flagyl 400mg brand order bactrim online order cephalexin 125mg sale

  44. Avohzp说道:

    buy aurogra no prescription sildenafil without a doctor’s prescription buy estradiol

  45. Qrpsiz说道:

    generic diflucan buy ciprofloxacin for sale buy generic cipro

  46. Gvqyjm说道:

    writing essays for money cheap research papers for sale hire essay writer

  47. Qzoxhs说道:

    order domperidone online cheap buy generic motilium sumycin 250mg generic

  48. Fzktfq说道:

    flomax online order zocor 20mg usa zocor 10mg pills

  49. Lawyze说道:

    buy buspar 10mg sale brand ezetimibe 10mg buy amiodarone without prescription

  50. Xczeie说道:

    buy generic ranitidine online generic meloxicam 15mg buy cheap generic celebrex

  51. Gdqjmk说道:

    allopurinol 100mg cost buy generic allopurinol over the counter buy generic rosuvastatin

  52. Thhzqg说道:

    buy imitrex online cheap buy levaquin medication buy avodart without a prescription

  53. Whshnm说道:

    astelin 10ml generic buy irbesartan online cheap avapro 150mg oral

  54. Wfdroi说道:

    cost nexium 40mg esomeprazole price order topamax 100mg sale

  55. Koqyhx说道:

    purchase pepcid generic buy losartan generic order prograf 5mg online cheap

  56. Chanmk说道:

    order xenical 120mg online cheap diltiazem us purchase diltiazem online

  57. Ezirbg说道:

    order medex generic paxil 10mg purchase maxolon without prescription

  58. Ilersu说道:

    buy generic amaryl buy cytotec sale etoricoxib 60mg tablet

  59. Yfsbpc说道:

    buy nortriptyline 25mg online order panadol generic purchase acetaminophen pills

  60. Erqybg说道:

    inderal ca buy ibuprofen pills plavix pill

  61. Wwgrmc说道:

    fosamax 35mg canada purchase fosamax online order nitrofurantoin 100 mg pill

  62. Yagyhp说道:

    baclofen 25mg drug buy baclofen 25mg online cheap ketorolac tablet

  63. Iyxudv说道:

    buy loratadine without a prescription priligy over the counter order generic priligy 60mg

  64. Wufusl说道:

    oral perindopril 4mg brand fexofenadine buy allegra 120mg online

  65. Ykohqb说道:

    dilantin order buy flexeril medication ditropan sale

  66. Zikuty说道:

    vardenafil 10mg sale where to buy digoxin without a prescription tizanidine tablet

  67. Rtpdwx说道:

    methylprednisolone tablets purchase adalat pills buy triamcinolone 4mg for sale

  68. Hpbxub说道:

    order clomid 100mg without prescription brand clomiphene imuran 25mg canada

  69. Zwquik说道:

    amantadine 100 mg price buy avlosulfon 100 mg generic avlosulfon pills

  70. Wdvooh说道:

    online slots for real money buy generic clavulanate online cheap synthroid without prescription

  71. Nunwub说道:

    online casino for real money blackjack online game ivermectin 3 mg over counter

  72. Kennzf说道:

    buy pantoprazole 20mg pills lisinopril 10mg pill buy generic pyridium

  73. Zutnyp说道:

    online casinos for usa players purchase ventolin inhalator generic ventolin inhalator canada

  74. Ullkvk说道:

    no deposit free spins lasix 100mg for sale buy lasix 40mg online cheap

  75. Xzbbwa说道:

    oral atorvastatin 20mg order amlodipine generic amlodipine 10mg sale

  76. Xyhbqx说道:

    purchase azithromycin sale buy omnacortil 5mg generic order generic gabapentin 100mg

  77. Nhhoyq说道:

    buy cefdinir 300mg pills order prevacid 30mg generic how to buy prevacid

  78. Ihmxym说道:

    buy isotretinoin 40mg generic amoxil 1000mg oral order zithromax 250mg pills

  79. Kozxwk说道:

    provigil 200mg cheap buy promethazine generic buy prednisone 5mg without prescription

  80. Gtokcv说道:

    cenforce 100mg cheap naprosyn 500mg for sale order chloroquine 250mg for sale

  81. Iczctn说道:

    micardis pills generic molnunat molnupiravir drug

  82. Mbocsx说道:

    oral cialis buy tadalafil 20mg generic sildenafil online order

  83. Egmnny说道:

    order omeprazole 10mg generic order lopressor 100mg pill order metoprolol generic

  84. Ihxkqs说道:

    order premarin 0.625mg pills order sildenafil pill buy sildenafil 100mg sale

  85. Izxrbj说道:

    vasotec 10mg drug lactulose bottles order duphalac bottless

  86. Fpegqa说道:

    buy generic xalatan online latanoprost ca buy generic exelon 6mg

  87. Qsyieo说道:

    purchase ferrous online order sotalol pills sotalol 40 mg us

  88. Zugcyn说道:

    buy mestinon 60 mg sale buy feldene 20 mg generic order maxalt generic

  89. Syhccy说道:

    prasugrel 10 mg drug order dramamine 50mg generic buy tolterodine 2mg generic

  90. Eefuqg说道:

    buy fludrocortisone 100 mcg online buy generic fludrocortisone online cost loperamide 2mg

  91. Grbfjr说道:

    buy generic etodolac 600 mg order colospa 135mg for sale buy pletal generic

  92. Bazpmw说道:

    generic dydrogesterone 10 mg duphaston 10 mg for sale cheap empagliflozin 10mg

  93. Mvhwzw说道:

    buy dipyridamole 25mg online dipyridamole online order buy pravastatin cheap

  94. Mhmaoj说道:

    order meloset 3mg online aygestin online order danazol 100 mg usa

  95. Tiybtw说道:

    aspirin 75mg oral buy aspirin generic imiquad online

  96. Kedfnc说道:

    buy generic precose online buy micronase 5mg generic order griseofulvin 250 mg online

  97. Aynwxl说道:

    mintop for sale new ed drugs best ed pills online

  98. Xeqnnl说道:

    ketotifen where to buy zaditor 1mg sale order imipramine 75mg sale

  99. Pfwwon说道:

    cialis 20mg ca viagra 100mg pills viagra 50mg tablet

  100. Zyoqdo说道:

    fenofibrate us buy fenofibrate sale buy tricor generic

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注