Method vs Functions, and other questions

前端 未结 8 1652
梦毁少年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 13:43

    Many answers are saying something along the lines that a method is what a function is called when it is defined on an object.

    While this is often true in the way the word is used when people talk about JavaScript or object oriented programming in general (see here), it is worth noting that in ES6 the term method has taken on a very specific meaning (see section 14.3 Method Definitions of the specs).


    Method Definitions

    A method (in the strict sense) is a function that was defined through the concise method syntax in an object literal or as a class method in a class declaration / expression:

    // In object literals:
    const obj = {
        method() {}
    };
    
    // In class declarations:
    class MyClass {
        method() {}
    }
    

    Method Specificities

    This answer gives a good overview about the specificities of methods (in the strict sense), namely:

    1. methods get assigned an internal [[HomeObject]] property which allows them to use super.
    2. methods are not created with a prototype property and they don't have an internal [[Construct]] method which means that they cannot be called with new.
    3. the name of a method does not become a binding in the method's scope.

    Below are some examples illustrating how methods (in the strict sense) differ from functions defined on objects through function expressions:

    Example 1

    const obj = {
        method() {
            super.test;         // All good!
        },
        ordinaryFunction: function ordinaryFunction() {
            super.test;         // SyntaxError: 'super' keyword unexpected here
        }
    };

    Example 2

    const obj = {
        method() {},
        ordinaryFunction: function ordinaryFunction() {}
    };
    
    console.log( obj.ordinaryFunction.hasOwnProperty( 'prototype' ) );  // true
    console.log( obj.method.hasOwnProperty( 'prototype' ) );            // false
    
    new obj.ordinaryFunction();     // All good !
    new obj.method();               // TypeError: obj.method is not a constructor

    Example 3

    const obj = {
        method() {
            console.log( method );
        },
        ordinaryFunction: function ordinaryFunction() {
            console.log( ordinaryFunction );
        }
    };
    
    obj.ordinaryFunction()  // All good!
    obj.method()            // ReferenceError: method is not defined

提交回复
热议问题