Home  >  Article  >  Web Front-end  >  What are methods and functions in javascript

What are methods and functions in javascript

青灯夜游
青灯夜游Original
2021-07-01 17:53:432628browse

In javascript, a function is an executable javascript code block that needs to be called by name; and a method is a javascript function called through an object, that is, a method is a relatively special function.

What are methods and functions in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Function (function) is an executable javascript code block that needs to be called by name. It can pass some data (parameters of the function) for processing, and then return some data (return value of the function), or it may not return data.

Method (method) is a javascript function called through an object. In other words, methods are also functions, just special functions. Suppose there is a function called fn and an object called obj, then you can define a method:

  obj.method = fn;

  obj.method();    //定义之后的调用

When the function and object are written together, the function (function) becomes a method (method). It can only be written in the form of methods in objects. Methods can be written in the form of functions. Functions cannot be written in objects. The correct way to write them is:

Result: This is a question pointed to by this. The first one is: {m: ƒ}, and the second one is: One: window

var o={                       //对象
       m:function(){          //方法
           console.log(this);
            f();              //方法里可以函数
            f:function f(){
                console.log(this)
            }
       }
   }
  o.m();    //对象o的m方法,this作为方法被调用,指向调用它的对象。作为函数调用指向window,或undefined(严格模式)

Incorrect writing:

Error: Uncaught SyntaxError: Unexpected identifier

var o={
       function m(){       //X  
           console.log(this);
            f();
            function f(){
                console.log(this)
            }
       }
   }

[Related recommendations: javascript learning tutorial

The above is the detailed content of What are methods and functions in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn