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
buy furosemide 100mg without prescription buy furosemide online diuretic ventolin online order
buy generic lexapro 20mg purchase naltrexone generic revia tablet
buy strattera 10mg online cheap buy atomoxetine for sale order sertraline online
azithromycin order online azithromycin 500mg canada buy cheap gabapentin
ursodiol 300mg for sale order cetirizine 5mg generic cetirizine 5mg ca
buy deltasone 20mg order amoxicillin 1000mg online buy generic amoxil 500mg
omeprazole sandoz capsule 20 mg the best antacids for reflux best medicine for stomach bloating
can you get contraceptive pill from pharmacy nice guidelines enlarged prostate medication for premature ejaculation
cymbalta buy online order glucotrol 5mg oral modafinil
best supplements for yeast overgrowth best hypertension medication combinations high blood pressure no insurance
order cyproheptadine 4 mg generic order generic cyproheptadine 4mg nizoral 200mg uk
valacyclovir how long to take once a week diabetic pill rx for diabetes
order provera 5mg medroxyprogesterone pills order microzide 25mg pills
is nicobloc fda approved buy pain pills online usa online pain management doctors prescriptions
femara 2.5mg without prescription abilify 20mg over the counter order aripiprazole 20mg generic
buy sleeping meds online can anyone buy sleeping pills buy diet pills online
alfuzosin over the counter alphabetical list of allergy medications best non prescription anti nausea
buy generic catapres for sale catapres 0.1mg price where to buy tiotropium without a prescription
popular acne prescriptions best cure for teenage acne trileptal uk
buy trimox generic buy generic trimox 500mg order clarithromycin generic
order rocaltrol generic buy tricor 200mg without prescription order fenofibrate 200mg sale
essay writing assistance owl essay writing cheap suprax
pay for a research paper online casinos online gambling
buy lamisil 250mg online casino no deposit bonus codes
aspirin 75mg generic order aspirin for sale luckyland slots
trazodone for sale trazodone 100mg for sale buy clindac a
buy generic tadacip 20mg order generic tadalafil generic indocin
buy retin paypal buy avana sale order avana 100mg sale
buy nolvadex pills nolvadex 20mg uk buy generic budesonide online
buy cleocin 300mg without prescription ed remedies purchase sildenafil pills
buy lamictal without prescription minipress 1mg drug purchase vermox for sale
flagyl 400mg brand order bactrim online order cephalexin 125mg sale
buy aurogra no prescription sildenafil without a doctor’s prescription buy estradiol
generic diflucan buy ciprofloxacin for sale buy generic cipro
writing essays for money cheap research papers for sale hire essay writer
order domperidone online cheap buy generic motilium sumycin 250mg generic
flomax online order zocor 20mg usa zocor 10mg pills
buy buspar 10mg sale brand ezetimibe 10mg buy amiodarone without prescription
buy generic ranitidine online generic meloxicam 15mg buy cheap generic celebrex
allopurinol 100mg cost buy generic allopurinol over the counter buy generic rosuvastatin
buy imitrex online cheap buy levaquin medication buy avodart without a prescription
astelin 10ml generic buy irbesartan online cheap avapro 150mg oral
cost nexium 40mg esomeprazole price order topamax 100mg sale
purchase pepcid generic buy losartan generic order prograf 5mg online cheap
order xenical 120mg online cheap diltiazem us purchase diltiazem online
order medex generic paxil 10mg purchase maxolon without prescription
buy generic amaryl buy cytotec sale etoricoxib 60mg tablet
buy nortriptyline 25mg online order panadol generic purchase acetaminophen pills
inderal ca buy ibuprofen pills plavix pill
fosamax 35mg canada purchase fosamax online order nitrofurantoin 100 mg pill
baclofen 25mg drug buy baclofen 25mg online cheap ketorolac tablet
buy loratadine without a prescription priligy over the counter order generic priligy 60mg
oral perindopril 4mg brand fexofenadine buy allegra 120mg online
dilantin order buy flexeril medication ditropan sale
vardenafil 10mg sale where to buy digoxin without a prescription tizanidine tablet
methylprednisolone tablets purchase adalat pills buy triamcinolone 4mg for sale
order clomid 100mg without prescription brand clomiphene imuran 25mg canada
amantadine 100 mg price buy avlosulfon 100 mg generic avlosulfon pills
online slots for real money buy generic clavulanate online cheap synthroid without prescription
online casino for real money blackjack online game ivermectin 3 mg over counter
buy pantoprazole 20mg pills lisinopril 10mg pill buy generic pyridium
online casinos for usa players purchase ventolin inhalator generic ventolin inhalator canada
no deposit free spins lasix 100mg for sale buy lasix 40mg online cheap
oral atorvastatin 20mg order amlodipine generic amlodipine 10mg sale
purchase azithromycin sale buy omnacortil 5mg generic order generic gabapentin 100mg
buy cefdinir 300mg pills order prevacid 30mg generic how to buy prevacid
buy isotretinoin 40mg generic amoxil 1000mg oral order zithromax 250mg pills
provigil 200mg cheap buy promethazine generic buy prednisone 5mg without prescription
cenforce 100mg cheap naprosyn 500mg for sale order chloroquine 250mg for sale
micardis pills generic molnunat molnupiravir drug
oral cialis buy tadalafil 20mg generic sildenafil online order
order omeprazole 10mg generic order lopressor 100mg pill order metoprolol generic
order premarin 0.625mg pills order sildenafil pill buy sildenafil 100mg sale
vasotec 10mg drug lactulose bottles order duphalac bottless
buy generic xalatan online latanoprost ca buy generic exelon 6mg
purchase ferrous online order sotalol pills sotalol 40 mg us
buy mestinon 60 mg sale buy feldene 20 mg generic order maxalt generic
prasugrel 10 mg drug order dramamine 50mg generic buy tolterodine 2mg generic
buy fludrocortisone 100 mcg online buy generic fludrocortisone online cost loperamide 2mg
buy generic etodolac 600 mg order colospa 135mg for sale buy pletal generic
generic dydrogesterone 10 mg duphaston 10 mg for sale cheap empagliflozin 10mg
buy dipyridamole 25mg online dipyridamole online order buy pravastatin cheap
order meloset 3mg online aygestin online order danazol 100 mg usa
aspirin 75mg oral buy aspirin generic imiquad online
buy generic precose online buy micronase 5mg generic order griseofulvin 250 mg online
mintop for sale new ed drugs best ed pills online
ketotifen where to buy zaditor 1mg sale order imipramine 75mg sale
cialis 20mg ca viagra 100mg pills viagra 50mg tablet
fenofibrate us buy fenofibrate sale buy tricor generic