What's the difference between a method and a function?

前端 未结 30 3252
粉色の甜心
粉色の甜心 2020-11-21 05:08

Can someone provide a simple explanation of methods vs. functions in OOP context?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 05:45

    Here is some explanation for method vs. function using JavaScript examples:

    test(20, 50); is function define and use to run some steps or return something back that can be stored/used somewhere.

    You can reuse code: Define the code once and use it many times.

    You can use the same code many times with different arguments, to produce different results.

    var x = myFunction(4, 3);   // Function is called, return value will end up in x
    
    function myFunction(a, b) {
        return a * b;          // Function returns the product of a and b
    }
    

    var test = something.test(); here test() can be a method of some object or custom defined a prototype for inbuilt objects, here is more explanation:

    JavaScript methods are the actions that can be performed on objects.

    A JavaScript method is a property containing a function definition.

    Built-in property/method for strings in javascript:

    var message = "Hello world!";
    var x = message.toUpperCase();
    //Output: HELLO WORLD!
    

    Custom example:

    function person(firstName, lastName, age, eyeColor) {
        this.firstName = firstName;  
        this.lastName = lastName;
        this.age = age;
        this.eyeColor = eyeColor;
        this.changeName = function (name) {
            this.lastName = name;
        };
    }
    
    something.changeName("SomeName"); //This will change 'something' objject's name to 'SomeName'
    

    You can define properties for String, Array, etc as well for example

    String.prototype.distance = function (char) {
        var index = this.indexOf(char);
    
        if (index === -1) {
            console.log(char + " does not appear in " + this);
        } else {
            console.log(char + " is " + (this.length - index) + " characters from the end of the string!");
        }
    };
    
    var something = "ThisIsSomeString"
    
    // now use distance like this, run and check console log
    
    something.distance("m");

    Some references: Javascript Object Method, Functions, More info on prototype

提交回复
热议问题