Home  >  Article  >  Web Front-end  >  Talk about multiple understandings of functions in JavaScript_javascript skills

Talk about multiple understandings of functions in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:41:481082browse

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 > &#63; 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.

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