前端web之JavaScript语法(4)

本节主要归纳总结JavaScript语法,主要包含:JS语法和JS对象两个部分。后续章节将分别总结JS HTML DOM,JS Browser DOM,JS Ajax。

显示输出

常用四种显示数据方式:

方式说明使用场景示例
window.alert()写入警告框使用警告框来显示数据在浏览器弹框显示输出:window.alert(a+b)
document.write()写入 HTML 输出。仅用于测试目的在HTML页面显示变量输出:document.write(a+b)
innerHTML写入 HTML 元素。更改 HTML 元素的 innerHTML 属性是在 HTML 中显示数据的常用方法。修改id为demo的HTML元素的内容:
document.getElementById("demo").innerHTML=a+b
console.log()写入浏览器控制台在浏览器控制台显示数据在浏览器console控制台打印输出:console.log(a+b)

基础语法

语句

分号分隔 JavaScript 语句,虽然不强制使用,但是建议使用增加可读性

注释

单行语句注释:以 // 开头
多行代码块注释:以 /* 开头,以 */ 结尾

变量

  • 使用let或者var关键字定义变量,ES6建议使用let定义变量。
  • 常用变量类型:Number,String,Boolean,Array,Object;可以指定类型,也可以使用默认的动态类型,即根据值动态判断数据类型。
  • typeof :运算符能返回数据类型
  • undefined:没有值的变量,其值是 undefined。任何变量均可通过设置值为 undefined 进行清空。
  • 空值 , 空的字符串变量既有值也有类型, 与undefined不通。
  • null:在 JavaScript 中,null 的数据类型是对象。可以通过设置值为 null 清空对象。undefined 与 null 的值相等,但类型不相等

运算符

运算符类型运算符说明示例
赋值运算符=赋值let a=1
+=加等a+=1,等同于a=a+1
++递加let a=2; a++
比较运算符==等于注意: let x=5; x == "5"为true
===严格等于,数值和类型都完全相同例如:let x=5; x === 5为ture,但是x === "5"为false
!=不相等注意: let x=5; x != "5"为false
!==不等值或不等型注意: let x=5; x != "5"为true

函数

定义函数

定义函数有两种方式:一种是直接使用关键字function定义函数,另一种是定义匿名函数然后将函数赋值给变量。
方式一:直接定义函数
函数通过 function 关键词进行定义,其后是函数名和括号 ();
圆括号可包括由逗号分隔的参数;
由函数执行的代码被放置在花括号中:{}

        <script>
            let a=3
            let b=2
            function testFunc(x, y)
            {
                return x ** y
            }
            document.getElementById("demo").innerHTML=testFunc(a, b)
        </script>

方式二:定义匿名函数

var abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
};

上述两种定义完全等价,注意第二种方式按照完整语法需要在函数体末尾加一个;,表示赋值语句结束。

关键字arguments

  • 关键字arguments,主要用于函数参数较多的场景。
    利用arguments,你可以获得调用者传入的所有参数。也就是说,即使函数不定义任何参数,还是可以拿到参数的值。
function foo(x) {
    console.log('x = ' + x); // 10
    for (var i=0; i<arguments.length; i++) {
        console.log('arg ' + i + ' = ' + arguments[i]); // 10, 20, 30
    }
}
foo(10, 20, 30);
  • 实际上arguments最常用于判断传入参数的个数。
    示例:
// foo(a[, b], c)
// 接收2~3个参数,b是可选参数,如果只传2个参数,b默认为null:
function foo(a, b, c) {
    if (arguments.length === 2) {
        // 实际拿到的参数是a和b,c为undefined
        c = b; // 把b赋给c
        b = null; // b变为默认值
    }
    // ...
}

关键字rest
ES6引入了rest关键字,函数传递参数较多时,可以用于获取指定参数外的其他参数。

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]

foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

rest只能用在最后面,前面用…标识,从运行结果可知,传入的参数先绑定a、b,多余的参数以数组形式交给变量rest。

条件判断

可使用如下条件语句:

  • if ,指定条件为 true时执行
  • else, 条件为 false时执行
  • else if, 第一个条件为false,且当前条件为true时执行
  • switch, 多个被执行的备选代码块
    break, break关键词,它会跳出 switch 代码块.它会“忽略” switch 代码块中的其他代码的执行
    default, 规定不存在 case 匹配时所运行的代码

例如:

        <script>
            switch (new Date().getDay()) {
            case 0:
                day = "星期天";
                break;
            case 1:
                day = "星期一";
                break;
            case 2:
                day = "星期二";
                break;
            case 3:
                day = "星期三";
                break;
            case 4:
                day = "星期四";
                break;
            case 5:
                day = "星期五";
                break;
            case 6:
                day = "星期六";
        } 
        console.log(day)  
        </script>

有时会需要不同的 case 来使用相同的代码, 此时不需要用break,case后面条件为空

        <script>
            switch (new Date().getDay()) {
            case 4:
            case 5:
                day = "周末快到了:)";
                break; 
            case 0:
            case 6:
                day = "今天是周末~";
                break;
            default: 
                day = "期待周末!";
        }
        console.log(day)
        </script>

循环

JavaScript 支持不同类型的循环:

  • for - 多次遍历代码块
  • for/in - 遍历对象属性
  • while - 当指定条件为 true 时循环一段代码块
  • do/while - 当指定条件为 true 时循环一段代码块

示例:

        <script>
            function testfunc(n)
            {
                let sum=0
                for(i=0; i<n; i++)
                    sum+=n
                return sum
            }
            console.log(testfunc(2))
        </script>

异常

异常关键字

  • try 语句使您能够测试代码块中的错误。
  • catch 语句允许您处理错误。
  • throw 语句允许您创建自定义错误。
  • finally 使您能够执行代码,在 try 和 catch 之后,无论结果如何。

Error 对象

error 对象提供两个有用的属性:name 和 message
示例:

        <script>
            function testfunc()
            {
                try{
                    n = document.getElementById("demo").value
                    console.log("input data: "+n)
                    sum = 0
                    for(i=0;i<n;i++)
                        sum += i
                    return sum
                }
                catch(err)
                {
                    console.log(err.message)
                }
                finally
                {
                    console.log("this is final")
                }
            }
            console.log(testfunc())
        </script>

JS面向对象

在 JavaScript 中,几乎“所有事物”都是对象。

创建对象

既可以直接创建;也可以使用new关键字创建。
以下两种创建对象方式等效:

  • 直接赋值创建对象
        <script>
            let person = {
                name: "Bruce Luck",
                age:34,
                high: 178
            }
            document.getElementById("message").innerHTML =
            person.name + " is " + person.age + " years old.";          
        </script>
  • new关键字创建对象
    <script>
        let person = new Object();
        person.age = 44;
        person.name = "Bruce Luck";
        person.high = "178";
        document.getElementById("message").innerHTML =
        person.name + " is " + person.age + " years old.";          
    </script>

对象方法

方法是能够在对象上执行的动作,是包含函数定义的属性。
创建对象方法的语法:

methodName : function() { 代码行 }

访问对象方法的语法:

objectName.methodName()

注意:
如果methodName不带(),则返回该方法的函数定义

例子:

   let person = {
       firstName: "Bruce",
       lastName : "Luck",
       age:34,
       high: 178, 
       fullName : function() {
           return this.firstName + " " + this.lastName;
       }
   }
   console.log(person.fullName) //访问 fullName 属性时没有使用 (),则将返回函数定义
   document.getElementById("message").innerHTML =
   person.fullName() + " is " + person.age + " years old."; 

属性访问

访问对象属性的三种方式
方式一:

objectName.property           // person.age

方式二:

objectName["property"]       // person["age"]

方式三:

objectName[expression]       // x = "age"; person[x]

使用for…in 语句遍历对象的属性

     let person = {
         "name": "Bruce Luck",
         "age":34,
         "high": 178
     }
     for (i in person)
     {
         console.log(i)
     }

this 关键词
在 JavaScript 中,被称为 this 的事物,指的是“拥有”当前代码的对象。
this 的值,在函数中使用时,是“拥有”该函数的对象。

function person(firstName, lastName, age, eyeColor) {
    this.firstName = firstName;  //this指person对象本身
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    };
}

JavaScript 访问器(Getter 和 Setter)
get关键字,返回对象的属性

   let person = {
       firstName: "Bruce",
       lastName : "Luck",
       age:34,
       high: 178, 
       get name() {
           return this.firstName + " " + this.lastName;
       }
   }
   console.log(person.name) 
   document.getElementById("message").innerHTML =
   person.name + " is " + person.age + " years old.";  

set关键字,设置对象的属性

	 let person = {
	     firstName: "Bruce",
	     lastName : "Luck",
	     age:34,
	     high: 178, 
	     set name(age) {
	         this.age = age
	     }
	 }
	 person.age = 234
	 console.log(person.age) 
	 document.getElementById("message").innerHTML =
	 person.name + " is " + person.age + " years old.";   

原型prototype

JavaScript对每个创建的对象都会设置一个原型,指向它的原型对象。
当我们用obj.xxx访问一个对象的属性时,JavaScript引擎先在当前对象上查找该属性,如果没有找到,就到其原型对象上找,如果还没有找到,就一直上溯到Object.prototype对象,最后,如果还没有找到,就只能返回undefined。

  • 所有 JavaScript 对象都从原型继承属性和方法。
    日期对象继承自 Date.prototype。数组对象继承自 Array.prototype。Person 对象继承自 Person.prototype。
  • Object.prototype 位于原型继承链的顶端:
    日期对象、数组对象和 Person 对象都继承自 Object.prototype。

例如,创建一个Array对象:

var arr = [1, 2, 3];

原型链:arr ----> Array.prototype ----> Object.prototype ----> null

例如,创建一个函数对象:

function foo() {
    return 0;
}

原型链:foo ----> Function.prototype ----> Object.prototype ----> null

使用 prototype 属性可以给对象构造器添加新属性

   function Person(name, age, high)
   {
       this.name = name;
       this.age = age;
       this.high = high;
   }
   Person.prototype.school = "Hubei"
   stu_a = new Person("Bruce", 34, 167)
   stu_b = new Person("Frank", 43, 177)
   console.log(stu_a.name + " is " + stu_a.school)
   document.getElementById("message").innerHTML =
   stu_b.name + " is in " + stu_b.school;  

使用 prototype 属性可以给对象构造器添加新方法

   function Person(first_name, second_name, age, high)
   {
       this.first_name = first_name;
       this.second_name = second_name;
       this.age = age;
       this.high = high;
   };
   Person.prototype.name = function() {
       return this.first_name + " " + this.second_name;
   };
   stu_a = new Person("Bruce","Xu", 34, 167);
   stu_b = new Person("Frank", "Xu", 43, 177);
   console.log(stu_a.name() + " is " + stu_a.age);
   document.getElementById("message").innerHTML =
   stu_b.name() + " is in " + stu_b.age; 

对象构造器

有时我们需要创建相同“类型”的许多对象的“蓝图”。创建一种“对象类型”的方法,是使用对象构造器函数。

  • 对象构造器类似与面向对象语言的类,通常使用大写首字母对构造器函数命名。
  • 通过 new 关键词调用构造器函数可以创建相同类型的对象.

示例:

    function Person(name, age, high)
    {
        this.name = name;
        this.age = age;
        this.high = high;
    }
    stu_a = new Person("Bruce", 34, 167)
    stu_b = new Person("Frank", 43, 177)
    console.log(stu_a.name + " is " + stu_a.age + " years old.")
    document.getElementById("message").innerHTML =
    stu_b.name + " is " + stu_b.age + " years old."; 

在构造器函数中,this 是没有值的。它是新对象的替代物。 当一个新对象被创建时,this 的值会成为这个新对象。
注意:如果不写new,这就是一个普通函数,它返回undefined。但是,如果写了new,它就变成了一个构造函数,它绑定的this指向新创建的对象,并默认返回this,也就是说,不需要在最后写return this;。

与向已有对象添加新属性不同,无法为对象构造器添加新属性,例如:

     function Person(name, age, high)
      {
          this.name = name;
          this.age = age;
          this.high = high;
      }
      stu_a = new Person("Bruce", 34, 167)
      stu_b = new Person("Frank", 43, 177)
      Person.school = "Tinghua University"
      console.log(stu_a.name + " is " + stu_a.school)//执行代码将会提示属性undefined

向构造器添加一个新属性,必须添加到构造器函数:

 function Person(name, age, high, school="Tianjin")
     {
         this.name = name;
         this.age = age;
         this.high = high;
         this.school = school
     }
     stu_a = new Person("Bruce", 34, 167)
     stu_a.school = "Bejing"
     stu_b = new Person("Frank", 43, 177)
     console.log(stu_a.name + " is " + stu_a.school)
     document.getElementById("message").innerHTML =
     stu_b.name + " is in " + stu_b.school;  

新对象方法

// 添加或更改对象属性
Object.defineProperty(object, property, descriptor)

// 添加或更改多个对象属性
Object.defineProperties(object, descriptors)

// 访问属性
Object.getOwnPropertyDescriptor(object, property)

// 以数组返回所有属性
Object.getOwnPropertyNames(object)

// 以数组返回所有可枚举的属性
Object.keys(object)

// 访问原型
Object.getPrototypeOf(object)

// 阻止向对象添加属性
Object.preventExtensions(object)

// 如果可将属性添加到对象,则返回 true
Object.isExtensible(object)

// 防止更改对象属性(而不是值)
Object.seal(object)

// 如果对象被密封,则返回 true
Object.isSealed(object)

// 防止对对象进行任何更改
Object.freeze(object)

// 如果对象被冻结,则返回 true
Object.isFrozen(object)

// 定义 getter
get: function() { return language }
// 定义 setter
set: function(value) { language = value }

示例:

   function Person(first_name, second_name, age, high)
   {
       count = 0
       this.first_name = first_name;
       this.second_name = second_name;
       this.age = age;
       this.high = high;
       this.name = function() {
           return this.first_name + " " + this.second_name;
       }
   };
   stu_a = new Person("Bruce","Xu", 34, 167);
   Object.defineProperty(stu_a, "school", {value: "wuhan un"})
   console.log(stu_a.name() + " is " + stu_a.school);

类class

class用法

关键字class从ES6开始正式被引入到JavaScript。

  • class的定义包含了构造函数constructor和方法.
  • 方法不再需要function关键字

例如,使用原型构建对象

function Student(name, age) {
    this.a = name
    this.b = age
    this.hello = function() {
        console.log(this.name + "age is: " + this.age)
    }
}
Student.prototype.newfunc = function () {
    alert.prototype('add new func')
}

使用关键字class定义:

class Student
{
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    hello()
    {
        console.log(this.name + "age is: " + this.age);  
    }
}

class继承

class子类继承父类,需要extends父类,并且在子类的构造函数中使用super()函数调用父类的构造方法。
示例:

class Student
{
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    hello()
    {
        console.log(this.name + "age is: " + this.age);  
    }

};
class PrimaryStudent extends Student {
    constructor(name, age, grade) {
    	super(name, age);//调用父类构造方法
        this.grade = grade;
    };
};

注意:super()调用父类构造方法必须在this关键字赋值之前

参考文献:
https://www.w3school.com.cn/js/index.asp
https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值