有人能用一个真实的例子来解释JavaScript中函数和方法的区别吗

Can someone please explain me the difference between function and method in JavaScript with a real examples?

本文关键字:JavaScript 解释 函数 区别 方法 真实 一个      更新时间:2023-09-26

我知道这是一个非常基本的问题,但由于我是初学者,我对它的了解非常有限。我试图通过谷歌搜索各种在线资源来理解它,但无法获得清晰的视图。提前感谢。

在JavaScript中,方法是在对象属性上设置的函数;不多不少。

window.f = function() {} // method of `window`
a = {
  g: function() {} // method of `a`
};
function x() {
  var h = function() {} // not a method, because it's in a local variable,
                        // not in an object attribute
  var b = { i: h };     // method of `b` now.
};