Method vs Functions, and other questions

前端 未结 8 1654
梦毁少年i
梦毁少年i 2020-11-27 13:26

With respect to JS, what\'s the difference between the two? I know methods are associated with objects, but am confused what\'s the purpose of functions? How does the syntax

8条回答
  •  再見小時候
    2020-11-27 14:01

    To answer your title question as to what is the difference between a 'function' and a 'method'.

    It's semantics and has to do with what you are trying to express.

    In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a 'method'.

    Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod(). Since we said that a function is an object, a function within a function can be considered a method of that function.

    You could say things like “I am going to use the save method of my object.” And "This save method accepts a function as a parameter.” But you generally wouldn't say that a function accepts a method as a parameter.

    Btw, the book JavaScript Patterns by Stoyan Stefanov covers your questions in detail, and I highly recommend it if you really want to understand the language. Here's a quote from the book on this subject:

    So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.

提交回复
热议问题