Method vs Functions, and other questions

前端 未结 8 1647
梦毁少年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:45

    A function executes a list of statements example:

     function add() { 
         var a = 2; 
         var b = 3;
         var c = a + b;
         return c;
     }
    

    1) A method is a function that is applied to an object example:

     var message = "Hello world!";
     var x = message.toUpperCase(); // .toUpperCase() is a built in function
    

    2) Creating a method using an object constructor. Once the method belongs to the object you can apply it to that object. example:

    function Person(first, last, age, eyecolor) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.eyeColor = eyecolor;
        this.name = function() {return this.firstName + " " + this.lastName;};
    }
    
    document.getElementById("demo").innerHTML = person.fullName(); // using the 
    method 
    

    Definition of a method: A method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.

提交回复
热议问题