JavaScript语法

2019-08-01  本文已影响0人  Recalcitrant

JavaScript语法

一、JS变量

1.变量

var varName = 值;
varName = 值;

以var声明变量为局部变量,不以var声明的变量为全局变量。

2.常量(静态变量)

一旦赋值就不可被修改。

const varName = 常量值;

3.数据类型

var length = 7; 
const PI = 3.1415926535898;
var lastName = "Gates";
var lastName = 'Gates';
var cars = ["Porsche", "Volvo", "BMW"];   
var x = {firstName:"Bill", lastName:"Gates"};

二、JS函数

function 函数名(参数列表)
{
    函数体
}

三、JS对象

var 对象名 = {名称1:值1, 名称2:值2, 名称3:值3, ......}

1.对象属性

JavaScript 对象中的名称:值对被称为属性。

示例:

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};

2.对象方法

对象也可以有方法,方法是在对象上执行的动作。方法以函数定义被存储在属性中。

示例:

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

3.对象访问器

访问器的作用

(1)JavaScript Getter(get 关键词)

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "en",
  get lang() {
    return this.language;
  }
};
console.info(person.lang)

(2)JavaScript Setter(set 关键词)

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "",
  set lang(lang) {
    this.language = lang;
  }
};
console.info(person.language)
person.lang = "en";
console.info(person.language)

4.对象构造器

function Student(name, age)
{
    this.name = name;
    this.age = age;
    this.sayHello = function()
    {
        console.info(this.name + "说:Hello!");
    }
}
var s1 = new Student("lisi", 100);
var s2 = new Student("zhangsan", 200)
s1.sayHello();
s2.sayHello();
console.info(s1);
console.info(s2);
运行结果

5.对象原型

(1)原型继承

由于无法为已有的对象构造器添加新属性,除非直接修改该构造器函数。对此可以采用原型继承。

JavaScript prototype 属性允许为对象构造器添加新属性或新方法:

function Person(name, age)
{
    this.name = name;
    this.age = age;
}

Person.prototype.username = "admin"
Person.prototype.shuo = function()
{
    console.info("Hello World!");
}

var u = new Person("张三", 20)

console.info(u['name']);
console.info(u['age']);
console.info(u['username']);
u.shuo();

console.info(u);
运行结果
function Person(name, age)
{
    this.name = name;
    this.age = age;
}

function User(username)
{
    this.username = username;
    this.shuo = function()
    {
        console.info("Hello World!");
    }
}

User.prototype = new Person("张三", 20)
var u = new User('admin');

console.info(u['name']);
console.info(u['age']);
console.info(u['username']);
u.shuo();

console.info(u);
运行结果

四、ES6新特性

1.箭头函数

var a = (v, h) => v + h;
console.info(a(5, 6));

2.类(语法糖)

3.继承(语法糖)

上一篇 下一篇

猜你喜欢

热点阅读