var 命令
var a; // undefined
var b = 1
function命令
function add(a, b) {
return a + b
}
const 命令
const a //报错,必须进行初始化
const b = 1
let 命令
let a // undefined
let b = 1
function add (a, b) {
return a + b
}
let c = add(1, 2)
exoprt/import 命令
[方式一]
export function foo() {}
export var name = "anan"
var bar = [1,2,3]
export {bar}
[方式二]
function foo(){}
var name = "anan"
var var = [1, 2, 3]
exoprt {foo, name, bar}
[方式三]
function foo() {}
exoprt {foo as foo1} // 导出时时命名
[方式四]
function foo() {}
exoprt default foo
[导入]
import {foo} form "xxx"
import fooFn from ‘xxx‘ // 随意命名
export default function foo() {}
export function bar() {}
export function baz() {}
import fooFn { bar, baz } from "module";
class命令
es6之前js没有类的概念,但可以通过构造函数来时类的功能
function Person(name, age) {
this.name = name
this.age = age
this.sayHello = function () {
console.log("name:" + this.name)
}
}
function Worker(job) {
this.job = job
this.sayJob = function () {
console.log(this.job)
}
}
Worker.prototype = new Person("anan", 20) // 利用原型链继承实现worker对Person方法和属性的继承
var teacher = new Worker("ananTea")
es6中提供了class关键字,提供了对类的支持
class Person {
constructor (name, age) {
this.name = name
this.age = age
}
sayHello() {
console.log(this.name)
}
}
var person = new Person("anan", 20)
person.sayName() // anan
分析
class关键字定义了Person类,constructor为该类的构造方法 sayHello为类方法,在使用new创建一个实例对象perosn时,会自动调用constructor构造方法,传入参数,返回实例对象,this指向的就是该实例对象
使用class定义的类的实例化相当于给Person.prototype添加属性和方法,实际上定义子类的所有方法都是定义在prototype属性上的
严格模式,在类和模块的内部默认的就是严格模式
class Person {
}
class Person {
constructor () {
}
}
class Person {
constructor () {
return Object.create(null)
}
}
new Person() instanceof Person // false
class Person {
constructor (name, age) {
this.name = name
this.age = age
}
sayHello () {
return this.name
}
}
var person = new Person("anan", 20)
console.log(person.sayHello()) // anan
person.hasOwnProperty("name") // true
person.hasOwnProperty("age") // true
person.hasOwnProperty("sayHello") // false
person.__proto__.hasOwnProperty("sayHello") // true
name和age都是person的自身的属性,而sayHello是原型对象的属性
class的取值函数(getter)和存值函数(setter)
class MyClass {
constructor {
}
get prop() {
return ‘getter‘
}
set prop(value) {
console.log(‘setter‘ + value)
}
}
let myclass = new MyClass()
myclass.prop = 123 // setter123
console.log(myclass.prop) // getter
class的静态方法
class Foo () {
static classMethod () {
return ‘hello‘
}
}
Foo.classMethod() // hello
var foo = new Foo()
// foo.classMethod // 报错
class Bar extends Foo {
}
Bar.classMethod() // hello
class的静态属性和实例属性
class Foo {
myProp = 40 // 即使没this只要在类的定义之中就是实例属性
constructor () {
console.log(this.myProp) // 40
}
}
Foo.prop = 1 // 类的属性
Foo.prop // 1
原文:https://www.cnblogs.com/kuishen/p/10998089.html