What is the usage of function in javascript

青灯夜游
Release: 2022-02-08 15:50:39
Original
12965 people have browsed it

Usage of function in JavaScript: 1. Use it as a regular function, the syntax is "function function name(){...}"; 2. Use it as an object attribute; 3. Use it as a constructor, Syntax "var obj = new function(){ ...}".

What is the usage of function in javascript

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

Perhaps one of the most difficult concepts to understand in javascript is the use of function. Through a lot of practice and practice, I slowly summarized the three uses of javascript function, as follows:

1. Use it as a regular function

function exception(){
  return  "error:";
}
var obj = result(); // 此处result作为常规函数来调用,obj获取到的是result函数的返回值;
Copy after login

2. Use it as an object attribute

The function in javascript is an instance of the Function type and is also an object. It can also be used as an attribute of other objects. When the function attribute of the object is called, the code in the function is executed. As follows:

function showMsg(){
     this.msg = "error"
     alert(this.msg);
}
var exception = new object;
exception.show = showMsg;
Copy after login

3. Use as a constructor

Custom classes and class instantiation in javascript are implemented in the definition of function, by using The form of new function returns an object instance.

var obj = new function(){ this.msg= "error";} // 调用匿名函数返回object实例
Copy after login

Or

function Exception(){
this.msg = "error";
this.show = function(){
alert(this.msg);
}
}
var exception = new Exception();
exception.show();
Copy after login

[Related recommendations: javascript learning tutorial]

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template