Home > Web Front-end > JS Tutorial > body text

Teach you a detailed explanation of how to get started with JavaScript in 10 minutes

黄舟
Release: 2017-03-08 15:06:13
Original
1150 people have browsed it

With the failure of the company’s internal technology sharing (JS advanced) vote, I will first translate a good JS introductory blog post to facilitate children who don’t know much about JS to quickly learn and master this magical language. .

Introduction

JavaScript is an object-oriented dynamic language. It is generally used to handle the following tasks:

  1. Modify web pages

  • Generate HTML and CSS

  • Generate dynamic HTML content

  • Generate some special effects

  • Provide user interaction interface

    • Generate user interaction components

    • Verify user input

    • Autofill form

  • Front-end application that can read local or remote data, such as //m.sbmmt.com /

  • Implement server-side programs like JAVA, C#, C++ through Nodejs

  • Implement distributed WEB programs, including front-end and server-side

  • The version of JavaScript currently supported by browsers is called "ECMAScript 5.1", or simply "ES5", but the next two versions are called "ES6" and "ES7" (or "ES2015" and "ES2016", as the new version is named after this year), which has a lot of additional features and improved syntax, is very worth looking forward to (and has been partially adopted by current browsers and back-end JS environmental support).

    This blog post is quoted from the book "Building Front-End Web Apps with Plain JavaScript".

    JavaScript types and constants

    JS has three value types: string, number and boolean. We can use a variable v to save different types of values ​​for comparison with typeof(v), typeof (v)===”number”.

    JS has 5 reference types: Object, Array, Function, Date and RegExp. Arrays, functions, dates, and regular expressions are special types of objects, but conceptually, dates and regular expressions are value types that are packaged into object form.

    Variables, arrays, function parameters and return values ​​do not need to be declared. They are usually not checked by the JavaScript engine and will be automatically type converted.

    The variable value may be:

    1. Data, such as string, number, boolean

    2. Reference of object: such as ordinary object , array, function, date, regular expression

    3. The special value null, which is often used as the default value for initialized object variables

    4. The special value undefined, the initial value that has been declared but not initialized

    string is a sequence of Unicode characters. String constants will be wrapped in single or double quotes, such as "Hello World!", "A3F0′, or the empty string "". Two string expressions can be connected using the + operator and Can be compared by equals:

    if (firstName + lastName === "James Bond")
    Copy after login

    The number of characters in the string can be obtained through the length attribute:

    console.log( "Hello world!".length);  // 12
    Copy after login

    All numeric values ​​​​are in 64-bit floating point numbers words. There is no clear type distinction between integers and floating point numbers. If a numeric constant is not a number, its value can be set to NaN ("not a number"), which can be determined using the isNaN method.

    Unfortunately. Yes, there was no Number.isInteger method until ES6, which was used to test whether a number is an integer. Therefore, in browsers that do not yet support it, to ensure that a numeric value is an integer, or a string of numbers is converted to For an integer, you must use the parseInt function. Similarly, a string containing decimals can be converted with the parseFloat method. The best way is to use String(n). Like Java, we also have two predefined Boolean values, true and false, and Boolean operator symbols: ! (not), && (and), || (or) when non-boolean values ​​and boolean values. When comparing, non-boolean values ​​will be converted implicitly. Empty strings, numbers 0, and undefined and null will be converted to false, and all other values ​​will be converted to true.

    Usually we need to use all. equal signs (=== and !==) instead of == and ! =. Otherwise, the number 2 is equal to the string "2", (2 == "2″) is true

    Both VAR= [] and var a = new Array() can define an empty array (Erhu: the former is recommended)

    VAR O ={} and var o = new Obejct() can both define an empty object. (Erhu: The former is still recommended). Note that an empty object {} is not really empty because it contains the Object.prototype inherited property. Therefore, a real empty object must be prototyped with Null, var o = Object.create. (null).

    Table 1 Type testing and conversion

    ##Variable scope

    In the current version of JavaScript ES5, there are two types Scope variables: global scope and function scope, no block scope. Therefore, you should avoid declaring variables inside a block

    function foo() {
      for (var i=0; i < 10; i++) {
        ...  // do something with i
      }
    }
    Copy after login

    We should write like this

    function foo() {
      var i=0;
      for (i=0; i < 10; i++) {
        ...  // do something with i
      }
    }
    Copy after login

    All variables should be in functions. The start declaration. Only in the next version of JavaScript, ES6, we can declare a block-level variable using the let keyword.

    严格模式

    从ES5开始,我们可以使用严格模式,获得更多的运行时错误检查。例如,在严格模式下,所有变量都必须进行声明。给未声明的变量赋值抛出异常。

    我们可以通过键入下面的语句作为一个JavaScript文件或script元素中的第一行开启严格模式:’use strict’;

    通常建议您使用严格模式,除非你的代码依赖于与严格的模式不兼容的库。

    不同类型的对象

    JS对象与传统的OO/UML对象不同。它们可以不通过类实例化而来。它们有属性、方法、键值对三种扩展。

    JS对象可以直接通过JSON产生,而不用实例化一个类。

    var person1 = { lastName:"Smith", firstName:"Tom"};
    var o1 = Object.create( null);  // an empty object with no slots
    Copy after login

    对象属性可以以两种方式获得:

    1. 使用点符号(如在C ++/ Java的):person1.lastName = “Smith”

    2. 使用MAP方式person1["lastName"] = “Smith”

    JS对象有不同的使用方式。这里有五个例子:

    1. 记录,例如,var myRecord = {firstName:”Tom”, lastName:”Smith”, age:26}

    2. MAP(也称为“关联数组”,“词典”或其他语言的“哈希表”)var numeral2number = {“one”:”1″, “two”:”2″, “three”:”3″}

    3. 非类型化对象

      var person1 = { lastName: "Smith", firstName: "Tom", getFullName: function () { return this.firstName +" "+ this.lastName; } };
      Copy after login
    4. 命名空间

      var myApp = { model:{}, view:{}, ctrl:{} };
      Copy after login

    可以由一个全局变量形式来定义,它的名称代表一个命名空间前缀。例如,上面的对象变量提供了基于模型 – 视图 – 控制器(MVC)架构模式,我们有相应的MVC应用程序的三个部分。

    正常的类

    数组

    可以用一个JavaScript数组文本进行初始化变量:

    var a = [1,2,3];

    因为它们是数组列表,JS数组可动态增长:我们可以使用比数组的长度更大的索引。例如,上面的数组变量初始化后,数组长度为3,但我们仍然可以操作第5个元素 a[4] = 7;

    我们可以通过数组的length属性得到数组长度:

    for (i=0; i < a.length; i++) { console.log(a[i]);} //1 2 3 undefined 7 `
    Copy after login

    我们可以通过 Array.isArray(a) 来检测一个变量是不是数组。

    通过push方法给数组追加元素:a.push( newElement);

    通过splice方法,删除指定位置的元素:a.splice( i, 1);

    通过indexOf查找数组,返回位置或者-1:if (a.indexOf(v) > -1) …

    通过for或者forEach(性能弱)遍历数组:

    var i=0;
    for (i=0; i < a.length; i++) {
      console.log( a[i]);
    }
    a.forEach(function (elem) {
      console.log( elem);
    })
    Copy after login

    通过slice复制数组:var clone = a.slice(0);

    Maps

    map(也称为“散列映射”或“关联数组’)提供了从键及其相关值的映射。一个JS map的键是可以包含空格的字符串:

    var myTranslation = { 
    "my house": "mein Haus", 
    "my boat": "mein Boot", 
    "my horse": "mein Pferd"
    }
    Copy after login

    通过Object.keys(m)可以获得map中所有的键:

    var i=0, key="", keys=[];
    keys = Object.keys( myTranslation);
    for (i=0; i < keys.length; i++) {
      key = keys[i];
      alert(&#39;The translation of &#39;+ key +&#39; is &#39;+ myTranslation[key]);
    }
    Copy after login

    通过直接给不存在的键赋值来新增元素:

    myTranslation["my car"] = "mein Auto";
    Copy after login

    通过delete删除元素:

    delete myTranslation["my boat"];
    Copy after login

    通过in搜索map:

    `if ("my bike" in myTranslation)  ...`
    Copy after login

    通过for或者forEach(性能弱)和Object.keys()遍历map:

    var i=0, key="", keys=[];
    keys = Object.keys( m);
    for (i=0; i < keys.length; i++) {
      key = keys[i];
      console.log( m[key]);
    }
    Object.keys( m).forEach( function (key) {
      console.log( m[key]);
    })
    Copy after login

    通过 JSON.stringify 将map序列化为JSON字符串,再JSON.parse将其反序列化为MAP对象 来实现复制:

    var clone = JSON.parse( JSON.stringify( m))
    Copy after login

    请注意,如果map上只包含简单数据类型或(可能嵌套)数组/map,这种方法效果很好。在其他情况下,如果map包含Date对象,我们必须写我们自己的clone方法。

    Functions

    JS函数是特殊的JS的对象,它具有一个可选的名字属性和一个长度属性(参数的数目)。我们可以这样知道一个变量是不是一个函数:

    if (typeof( v) === "function") {...}
    Copy after login

    JS函数可以保存在变量里、被当作参数传给其他函数,也可以被其他函数作为返回值返回。JS可以被看成一个函数式语言,函数在里面可以说是一等公民。

    正常的定义函数方法是用一个函数表达式给一个变量赋值:

    var myFunction = function theNameOfMyFunction () {...}
    function theNameOfMyFunction () {...}
    Copy after login

    其中函数名(theNameOfMyFunction)是可选的。如果省略它,其就是一个匿名函数。函数可以通过引用其的变量调用。在上述情况下,这意味着该函数通过myFunction()被调用,而不是通过theNameOfMyFunction()调用。

    JS函数,可以嵌套内部函数。闭包机制允许在函数外部访问函数内部变量,并且创建闭包的函数会记住它们。

    当执行一个函数时,我们可以通过使用内置的arguments参数,它类似一个参数数组,我们可以遍历它们,但由于它不是常规数组,forEach无法遍历它。arguments参数包含所有传递给函数的参数。我们可以这样定义一个不带参数的函数,并用任意数量的参数调用它,就像这样:

    var sum = function () {
      var result = 0, i=0;
      for (i=0; i < arguments.length; i++) {
        result = result + arguments[i];
      }
      return result;
    };
    console.log( sum(0,1,1,2,3,5,8));  // 20
    Copy after login

    prototype原型链可以访问函数中的每一个元素,如Array.prototype.forEach(其中Array代表原型链中的数组的构造函数)。

    var numbers = [1,2,3];  // create an instance of Array
    numbers.forEach( function (n) {
      console.log( n);
    });
    Copy after login

    我们还可以通过原型链中的prototype.call方法来处理:

    var sum = function () {
      var result = 0;
      Array.prototype.forEach.call( arguments, function (n) {
        result = result + n;
      });
      return result;
    };
    Copy after login

    Function.prototype.apply是Function.prototype.call的一个变种,其只能接受一个参数数组。

    立即调用的JS函数表达式优于使用纯命名对象,它可以获得一个命名空间对象,并可以控制其变量和方法哪些可以外部访问,哪些不是。这种机制也是JS模块概念的基础。在下面的例子中,我们定义了一个应用程序,它对外暴露了指定的元素和方法:

    myApp.model = function () {
      var appName = "My app&#39;s name";
      var someNonExposedVariable = ...;
      function ModelClass1 () {...}
      function ModelClass2 () {...}
      function someNonExposedMethod (...) {...}
      return {
        appName: appName,
        ModelClass1: ModelClass1,
        ModelClass2: ModelClass2
      }
    }();  // immediately invoked
    Copy after login

    这种模式在WebPlatform.org被当作最佳实践提及://m.sbmmt.com/

    定义和使用类

    类是在面向对象编程的基础概念。对象由类实例化而来。一个类定义了与它创建的对象的属性和方法。

    目前在JavaScript中没有明确的类的概念。JavaScript中定义类有很多不同的模式被提出,并在不同的框架中被使用。用于定义类的两个最常用的方法是:

    构造函数法,它通过原型链方法来实现继承,通过new创建新对象。这是Mozilla的JavaScript指南中推荐的经典方法。

    工厂方法:使用预定义的Object.create方法创建类的新实例。在这种方法中,基于构造函数继承必须通过另一种机制来代替。

    当构建一个应用程序时,我们可以使用这两种方法创建类,这取决于应用程序的需求 。mODELcLASSjs是一个比较成熟的库用来实现工厂方法,它有许多优点。(基于构造的方法有一定的性能优势)

    ES6中构造函数法创建类

    在ES6,用于定义基于构造函数的类的语法已推出(新的关键字类的构造函数,静态类和超类)。这种新的语法可以在三个步骤定义一个简单的类。

    基类Person 定义了两个属性firstName 和lastName,以及实例方法toString和静态方法checkLastName:

    class Person {
      constructor( first, last) {
        this.firstName = first;
        this.lastName = last;
      }
      toString() {
        return this.firstName + " " +
            this.lastName;
      }
      static checkLastName( ln) {
        if (typeof(ln)!=="string" || 
            ln.trim()==="") {
          console.log("Error: " +
              "invalid last name!");
        }
      }
    }
    Copy after login

    类的静态属性如下定义:

    Person.instances = {};
    Copy after login
    Copy after login

    一个子类定义的附加属性和可能会覆盖超类的方法:

    class Student extends Person {
      constructor( first, last, studNo) {
        super.constructor( first, last);
        this.studNo = studNo; 
      }
      // method overrides superclass method
      toString() {
        return super.toString() + "(" +
            this.studNo +")";
      }
    }
    Copy after login

    ES5中构造函数法创建类

    在ES5,我们可以以构造函数的形式定义一个基于构造函数的类结构,下面是Mozilla的JavaScript指南中推荐的编码模式。此模式需要七个步骤来定义一个简单的类结构。由于这种复杂的模式可能很难记住,我们可能需要使用cLASSjs之类的库来帮助我们。

    首先定义构造函数是隐式创建一个新的对象,并赋予它相应的值:

    function Person( first, last) {
      this.firstName = first; 
      this.lastName = last; 
    }
    Copy after login

    这里的this指向新创建的对象。

    在原型中定义实例方法:

    Person.prototype.toString = function () {
      return this.firstName + " " + this.lastName;
    }
    Copy after login

    可以在构造函数中定义静态方法,也可以用.直接定义:

    Person.checkLastName = function (ln) {
      if (typeof(ln)!=="string" || ln.trim()==="") {
        console.log("Error: invalid last name!");
      }
    }
    Copy after login

    定义静态属性:

    Person.instances = {};
    Copy after login
    Copy after login

    定义子类并增加属性:

    function Student( first, last, studNo) {
      // invoke superclass constructor
      Person.call( this, first, last);
      // define and assign additional properties
      this.studNo = studNo;  
    }
    Copy after login

    通过Person.call( this, …) 来调用基类的构造函数。

    将子类的原型链改为基类的原型链,以实现实例方法的继承(构造函数得改回来):

    // Student inherits from Person
    Student.prototype = Object.create( 
        Person.prototype);
    // adjust the subtype&#39;s constructor property
    Student.prototype.constructor = Student;
    Copy after login

    通过Object.create( Person.prototype) 我们基于 Person.prototype创建了一个新的对象原型。

    定义覆盖基类方法的子类方法:

    Student.prototype.toString = function () {
      return Person.prototype.toString.call( this) +
          "(" + this.studNo + ")";
    };
    Copy after login

    最后通过new关键字来实例化一个类

    var pers1 = new Person("Tom","Smith");
    Copy after login

    JavaScript的prototype

    prototype是函数的一个属性(每个函数都有一个prototype属性),这个属性是一个指针,指向一个对象。它是显示修改对象的原型的属性。

    __proto__是一个对象拥有的内置属性(prototype是函数的内置属性。__proto__是对象的内置属性),是JS内部使用寻找原型链的属性。

    每个对象都有个constructor属性,其指向的是创建当前对象的构造函数。

    工厂模式创建类

    在这种方法中,我们定义了一个JS对象Person,并在其内部定义了一个create方法用来调用Object.create来创建类。

    var Person = {
      name: "Person",
      properties: {
        firstName: {range:"NonEmptyString", label:"First name", 
            writable: true, enumerable: true},
        lastName: {range:"NonEmptyString", label:"Last name", 
            writable: true, enumerable: true}
      },
      methods: {
        getFullName: function () {
          return this.firstName +" "+ this.lastName; 
        }
      },
      create: function (slots) {
        // create object
        var obj = Object.create( this.methods, this.properties);
        // add special property for *direct type* of object
        Object.defineProperty( obj, "type", 
            {value: this, writable: false, enumerable: true});
        // initialize object
        Object.keys( slots).forEach( function (prop) {
          if (prop in this.properties) obj[prop] = slots[prop];
        })
        return obj;
      }
    };
    Copy after login

    这样,我们就有了一个Person的工厂类,通过调用create方法来实例化对象。

    var pers1 = Person.create( {firstName:"Tom", lastName:"Smith"});
    Copy after login

    The above is the detailed content of Teach you a detailed explanation of how to get started with JavaScript in 10 minutes. 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