


Talk about multiple understandings of functions in JavaScript_javascript skills
Function in JavaScript has multiple meanings. It may be a constructor (constructor), which plays the role of an object template; may be a method of the object (method), which is responsible for sending messages to the object. may also be a function , yes it is a function, a function that exists independently and can be called without any relationship with the object.
Due to the compromise of the language designer, some class-related features have been added to JavaScript to make JavaScript look like Java and can be "object-oriented". Although JavaScript has added new and this, there is no class (ES has added it). Finally, function temporarily takes on the task of class.
Semantics 1: function as constructor
/** * 页签 * * @class Tab * @param nav {string} 页签标题的class * @param content {string} 页面内容的class * */ function Tab(nav, content) { this.nav = nav; this.content = content; } Tab.prototype.getNav = function() { return this.nav; }; Tab.prototype.setNav = function(nav) { this.nav = nav; }; Tab.prototype.add = function() { }; // 创建对象 var tab = new Tab('tab-nav', 'tab-content');
A class Tab is defined here and an object tab is created. Function, this, new are used above. this, new are keywords in common object-oriented languages, and function here plays the role of class in traditional object-oriented languages. Of course, the naming of identifiers at this time generally follows the "first letter capitalization" rule.
Semantics 2: function as an object method
Since objects can be created directly in JavaScript without classes, there are two ways to add methods to objects. The first is to define the class first and hang the methods on the prototype, such as Tab in the above example. The prototype has getNav, setNav and add methods. There is another way to add methods directly on this within the function.
function Tab(nav, content) { this.nav = nav this.content = content this.getNav = function() { // ... } this.setNav = function() { // ... } this.add = function() { // ... } }
Here Tab is the semantics, this.getNav/this.setNav/this.add is the semantics, as a method of the object. In addition, objects and their methods can be defined directly
var tab = { nav: '', content: '', getNav: function() { // ... }, setNav: function() { // ... }, add: function() { // ... } }
tab.getNav/tab.setNav/tab.add are semantic, as methods of the object tab.
Semantics 3: As an independent function
/* * 判断对象是否是一个空对象 * @param obj {Object} * @return {boolean} */ function isEmpty(obj) { for (var a in obj) { return false } return true } // 定义一个模块 ~function() { // 辅助函数 function now() { return (new Date).getTime() } // 模块逻辑... }(); // 采用CommonJS规范的方式定义一个模块 define(require, exports, moduel) { // 辅助函数 function now() { return (new Date).getTime() } // 模块逻辑... })
isEmpty exists as a global function, and now in the module definition exists as a local function. Whether isEmpty or now, the function here refers to a function. It does not depend on objects and classes and can be called independently.
Semantics 4: Anonymous function definition module
// 全局命名空间 var RUI = {} // ajax.js ~function(R) { // 辅助函数... ajax = { request: function() { // ... } getJSON: function() { // ... } ... } // 暴露出模块给 R R.ajax = ajax }(RUI); // event.js ~function(R) { // 辅助函数... // 事件模块定义... // 暴露出模块给 R R.event = event }(RUI); // dom.js ~function(R) { // 辅助函数... // DON模块定义... // 暴露出模块给 R R.dom = dom }(RUI);
After the anonymous function here is executed, the API object is exposed to the RUI. No matter how much work is done in the anonymous function, it cannot be seen outside the corresponding anonymous function, and there is no need to pay attention to it. The final concern is the public API methods. As long as you understand the parameters and meaning of these methods, you can use it immediately.
Semantics 5: Anonymous functions handle certain special effects such as processing some data without exposing too many variables
// 判断IE版本的hack方式 var IEVersion = function() { var undef, v = var div = document.createElement('div') var all = div.getElementsByTagName('i') while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[] ); return v > ? v : undef }();
In the end, there is only one result IEVersion, and some local variables used inside the anonymous function can all be isolated. This method is very effective and compact for some temporary data processing.
Summary:
JavaScript was designed by Eich in days. It was originally a short and compact script/functional language. For marketing reasons, in order to cater to Java, some Java-like object-oriented features were added (constructor, this, new). This and new are copied over, but the functions of class are handed over to function. As a result, JavaScript functions are confusing. Sometimes they are used to define classes, and sometimes they are used as methods or functions. Some people also discovered that it can be used to define modules and so on.
All this ended with the arrival of ES. The reserved word "class" in ES was finally implemented. It is recommended to use class to define classes. There is also the extend keyword, which basically brings “class inheritance” over. Douglas commented at the Nordic.js conference that one of the worst designs of ES is class. In addition, it is not recommended to use this and new. This shows that he still favors the use of functional language to write JavaScript, rather than object-oriented based on classes. .
The above content is my personal multiple understanding of functions in JavaScript. Friends who have different understandings are welcome to share and learn and progress together.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)