Home > Article > Web Front-end > What is the usage of function in javascript
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(){ ...}".
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函数的返回值;
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;
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实例
Or
function Exception(){ this.msg = "error"; this.show = function(){ alert(this.msg); } } var exception = new Exception(); exception.show();
[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!