
简单的基本功能
这是一个不带参数的简单函数:
| 1 2 3 4 5 | 
functionhello() {
   console.log('hello there stranger, how are you?');
 }
 
 hello();
 | 
 
这是一个带有一个参数的函数:
| 1 2 3 4 5 | 
functiongreet(person) {
   console.log(`hi there ${person}.`);
 }
 
 greet('megan');
 | 
 
我们可以有多个参数,如下所示:
| 1 2 3 4 5 | 
functiongreetfullname(fname, lname) {
   console.log(`hi there ${fname} ${lname}.`);
 }
 
 greetfullname('megan', 'paffrath');
 | 
 
函数表达式
函数表达式只是编写函数的另一种方式。他们的工作方式仍然与上面相同:
| 1 2 3 4 5 | 
constsquare = function(x) {
    returnx * x;
 };
 
 square(2); 
 | 
 
高阶函数
这些函数与其他函数一起运行/在其他函数上运行,也许它们:
将另一个函数作为参数的函数的示例是:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 
functioncalltwice(func) {
   func();
   func();
 }
 
 let laugh = function() {
   console.log('haha');
 };
 
 calltwice(laugh);
 
 functionrolldie() {
   constroll = math.floor(math.random() * 6) + 1;
   console.log(roll);
 }
 
 calltwice(rolldie);
 | 
 
函数返回函数的一个例子是:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 
functionmakemysteryfunc() {
   constrand = math.random();
   if(rand > 0.5) {
     returnfunction() {
       console.log('you win');
     };
   } else{
     returnfunction() {
       alert('you have been infected by a computer virus');
       while(true) {
         alert('stop trying to close this window.');
       }
     };
   }
 }
 
 let returnedfunc = makemysteryfunc();
 returnedfunc();
 | 
 
另一个(更有用的例子)是:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 
functionmakebetweenfunc(min, max) {
   returnfunction(num) {
     returnnum >= min && num 
 
 
 
 <h2>
   
   
   方法
 </h2>
 
 <p>我们可以添加函数作为对象的属性(这些称为方法)。</p>
 
 <p>例如:<br></p>
 
 <pre class="brush:php;toolbar:false">constmymath = {
   pi: 3.14,
   square: function(num) {
     returnnum * num;
   },
   
   cube(num) {
     returnnum ** 3;
   },
 };
 | 
 
这
“this”主要在对象的方法中使用。它用于引用对象的属性。
| 1 2 3 4 5 6 7 8 9 10 11 | 
constperson = {
   first: 'abby',
   last: 'smith',
   fullname() {
     return`${this.first} ${this.last}`;
   },
 };
 
 person.fullname(); 
 person.lastname = 'elm';
 person.fullname(); 
 | 
 
注意,在对象之外,“this”指的是顶级窗口对象。要查看其中包含的内容,请在控制台中输入。通用函数也存储在 this 对象中:
| 1 2 3 4 5 6 | 
functionhowdy() {
   console.log('HOWDY');
 }
 
 this.howdy(); 
 |