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

89 Responses

  1. Hddlei说道:

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

  2. Qzlthe说道:

    buy generic lexapro 20mg purchase naltrexone generic revia tablet

  3. Lgcyaz说道:

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

  4. Wsrues说道:

    azithromycin order online azithromycin 500mg canada buy cheap gabapentin

  5. Ukmjwa说道:

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

  6. Kdnmgm说道:

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

  7. Warkfv说道:

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

  8. Bvqlrw说道:

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

  9. Mrfyes说道:

    cymbalta buy online order glucotrol 5mg oral modafinil

  10. Pjaclh说道:

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

  11. Abifrd说道:

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

  12. Iaczui说道:

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

  13. Yceeqs说道:

    order provera 5mg medroxyprogesterone pills order microzide 25mg pills

  14. Vmpvon说道:

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

  15. Rzafhz说道:

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

  16. Qssovo说道:

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

  17. Pfjvui说道:

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

  18. Ovmypb说道:

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

  19. Hrrbgs说道:

    popular acne prescriptions best cure for teenage acne trileptal uk

  20. Qikmkl说道:

    buy trimox generic buy generic trimox 500mg order clarithromycin generic

  21. Qsgwaf说道:

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

  22. Klxzxm说道:

    essay writing assistance owl essay writing cheap suprax

  23. Oqpzkf说道:

    pay for a research paper online casinos online gambling

  24. Cwrxkv说道:

    buy lamisil 250mg online casino no deposit bonus codes

  25. Ysndpy说道:

    aspirin 75mg generic order aspirin for sale luckyland slots

  26. Prwogw说道:

    trazodone for sale trazodone 100mg for sale buy clindac a

  27. Jqgwno说道:

    buy generic tadacip 20mg order generic tadalafil generic indocin

  28. Pjmuvj说道:

    buy retin paypal buy avana sale order avana 100mg sale

  29. Qqktlg说道:

    buy nolvadex pills nolvadex 20mg uk buy generic budesonide online

  30. Sodbru说道:

    buy cleocin 300mg without prescription ed remedies purchase sildenafil pills

  31. Vaafrt说道:

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

  32. Aalthx说道:

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

  33. Avohzp说道:

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

  34. Qrpsiz说道:

    generic diflucan buy ciprofloxacin for sale buy generic cipro

  35. Gvqyjm说道:

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

  36. Qzoxhs说道:

    order domperidone online cheap buy generic motilium sumycin 250mg generic

  37. Fzktfq说道:

    flomax online order zocor 20mg usa zocor 10mg pills

  38. Lawyze说道:

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

  39. Xczeie说道:

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

  40. Gdqjmk说道:

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

  41. Thhzqg说道:

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

  42. Whshnm说道:

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

  43. Wfdroi说道:

    cost nexium 40mg esomeprazole price order topamax 100mg sale

  44. Koqyhx说道:

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

  45. Chanmk说道:

    order xenical 120mg online cheap diltiazem us purchase diltiazem online

  46. Ezirbg说道:

    order medex generic paxil 10mg purchase maxolon without prescription

  47. Ilersu说道:

    buy generic amaryl buy cytotec sale etoricoxib 60mg tablet

  48. Yfsbpc说道:

    buy nortriptyline 25mg online order panadol generic purchase acetaminophen pills

  49. Erqybg说道:

    inderal ca buy ibuprofen pills plavix pill

  50. Wwgrmc说道:

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

  51. Yagyhp说道:

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

  52. Iyxudv说道:

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

  53. Wufusl说道:

    oral perindopril 4mg brand fexofenadine buy allegra 120mg online

  54. Ykohqb说道:

    dilantin order buy flexeril medication ditropan sale

  55. Zikuty说道:

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

  56. Rtpdwx说道:

    methylprednisolone tablets purchase adalat pills buy triamcinolone 4mg for sale

  57. Hpbxub说道:

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

  58. Zwquik说道:

    amantadine 100 mg price buy avlosulfon 100 mg generic avlosulfon pills

  59. Wdvooh说道:

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

  60. Nunwub说道:

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

  61. Kennzf说道:

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

  62. Zutnyp说道:

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

  63. Ullkvk说道:

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

  64. Xzbbwa说道:

    oral atorvastatin 20mg order amlodipine generic amlodipine 10mg sale

  65. Xyhbqx说道:

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

  66. Nhhoyq说道:

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

  67. Ihmxym说道:

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

  68. Kozxwk说道:

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

  69. Gtokcv说道:

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

  70. Iczctn说道:

    micardis pills generic molnunat molnupiravir drug

  71. Mbocsx说道:

    oral cialis buy tadalafil 20mg generic sildenafil online order

  72. Egmnny说道:

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

  73. Ihxkqs说道:

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

  74. Izxrbj说道:

    vasotec 10mg drug lactulose bottles order duphalac bottless

  75. Fpegqa说道:

    buy generic xalatan online latanoprost ca buy generic exelon 6mg

  76. Qsyieo说道:

    purchase ferrous online order sotalol pills sotalol 40 mg us

  77. Zugcyn说道:

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

  78. Syhccy说道:

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

  79. Eefuqg说道:

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

  80. Grbfjr说道:

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

  81. Bazpmw说道:

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

  82. Mvhwzw说道:

    buy dipyridamole 25mg online dipyridamole online order buy pravastatin cheap

  83. Mhmaoj说道:

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

  84. Tiybtw说道:

    aspirin 75mg oral buy aspirin generic imiquad online

  85. Kedfnc说道:

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

  86. Aynwxl说道:

    mintop for sale new ed drugs best ed pills online

  87. Xeqnnl说道:

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

  88. Pfwwon说道:

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

  89. Zyoqdo说道:

    fenofibrate us buy fenofibrate sale buy tricor generic

发表回复

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

CAPTCHAis initialing...
退出移动版