登录
首页 >  文章 >  前端

JavaScript:函数、函数表达式、对象、方法和 this

来源:dev.to

时间:2024-08-07 10:15:52 343浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《JavaScript:函数、函数表达式、对象、方法和 this》,以下内容主要包含等知识点,如果你正在学习或准备学习文章,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

JavaScript:函数、函数表达式、对象、方法和 this

简单的基本功能

这是一个不带参数的简单函数:

function hello() {
  console.log('hello there stranger, how are you?');
}

hello();

这是一个带有一个参数的函数:

function greet(person) {
  console.log(`hi there ${person}.`);
}

greet('megan');

我们可以有多个参数,如下所示:

function greetfullname(fname, lname) {
  console.log(`hi there ${fname} ${lname}.`);
}

greetfullname('megan', 'paffrath');

函数表达式

函数表达式只是编写函数的另一种方式。他们的工作方式仍然与上面相同:

const square = function(x) {
   return x * x;
};

square(2); // 4

高阶函数

这些函数与其他函数一起运行/在其他函数上运行,也许它们:

  • 接受其他函数作为参数
  • 返回一个函数

将另一个函数作为参数的函数的示例是:

function calltwice(func) {
  func();
  func();
}

let laugh = function () {
  console.log('haha');
};

calltwice(laugh);
// haha
// haha

function rolldie() {
  const roll = math.floor(math.random() * 6) + 1;
  console.log(roll);
}

calltwice(rolldie);
// random number
// random number

函数返回函数的一个例子是:

function makemysteryfunc() {
  const rand = math.random();
  if (rand > 0.5) {
    return function () {
      console.log('you win');
    };
  } else {
    return function () {
      alert('you have been infected by a computer virus');
      while (true) {
        alert('stop trying to close this window.');
      }
    };
  }
}

let returnedfunc = makemysteryfunc();
returnedfunc();

另一个(更有用的例子)是:

function makebetweenfunc(min, max) {
  return function (num) {
    return num >= min && num <= max;
  };
}

const isbetween = makebetweenfunc(100, 200);
// isbetween(130); // true
// isbetween(34); // false

方法

我们可以添加函数作为对象的属性(这些称为方法)。

例如:

const mymath = {
  pi: 3.14,
  square: function (num) {
    return num * num;
  },
  // note the 2 diff ways of defining methods
  cube(num) {
    return num ** 3;
  },
};

“this”主要在对象的方法中使用。它用于引用对象的属性。

const person = {
  first: 'abby',
  last: 'smith',
  fullname() {
    return `${this.first} ${this.last}`;
  },
};

person.fullname(); // "abby smith"
person.lastname = 'elm';
person.fullname(); // "abby elm"

注意,在对象之外,“this”指的是顶级窗口对象。要查看其中包含的内容,请在控制台中输入。通用函数也存储在 this 对象中:

// defined on its own (outside of an object)
function howdy() {
  console.log('HOWDY');
}

this.howdy(); // HOWDY

终于介绍完啦!小伙伴们,这篇关于《JavaScript:函数、函数表达式、对象、方法和 this》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>