简单使用类
类
类表达式
如何创建类表达式
const Person = class {
	constructor() {
		console.log("")
	}
} // 类表达式
为类设置别名
const Person = class  P {
	constructor() {
		console.log("")
	}
} // 类表达式
new Person()
console.log(P) // P is not defined
// 
const Person = class  P {
	constructor() {
		console.log(P)
		console.log("")
	}
} // 类表达式
new Person() // 成功输出
在设置过别名后,下次类的名字修改,但是别名没有修改的情况下依然可以使用!!!而且使用别名和类是等同的
const Person = class  P {
	constructor() {
		p.name = "kangkang" 
		console.log("this.name")
	}
} // 类表达式
自执行的类
const Person = new class P {
	constructor() {
		
	}
}() //
getter
ES5中的getter和setter
- 
在对象字面量中书写get/set方法 const obj = { name: '', get name() { return this.name }, set name(val) { this.name = val } } obj.name = 333 // 当属性和get方法同名时出现栈溢出 const obj = { _name: '', get name() { return this._name }, set name(val) { this._name = val } } obj.name =333 // 在get中拦截了访问name要做的事情
- 
Object.defineProperty Object.defineProperty(obj,"name",{ value: "kangkang", enumerable: true // 可被遍历到,默认为false })let obj = {_name: "kangkang"} Object.defineProperty(obj,"name",{ get: function() { return this._name }, set: function(val) { this._name = val } }) obj.name = "xiaojun" console.log(obj.name) //xiaojun
ES6中书写
class Person {
	constructor () {
		this._name =""
	}
	get name() {
		return this._name
	}
	set name(val) {
		this._name = val
	} 
}
const person = new Person()
console.log(person.name = "kangkang") //kangkang
例
class AudioPlay {
            constructor() {
                this._status = 0
                this.status = 0
                this.init()
            }
            init() {
                let audio = new Audio()
                audio.oncanplay = () => {
                    this._status = 1
                }
            }
            get status() {
                return this._status
            }
            set status(val) {
                let statusValue = {
                    0: "暂停",
                    1: "播放",
                    2: "停止"
                }
                let btn =document.querySelector(".btn")
                btn.innerText = statusValue[val]
                this._status = val
            }
        }
        let audio = new AudioPlay()
        audio.status = 2
name属性和new.traget属性
const people =  class  {
	
}
console.log(people.name)
// people
const people =  class P {
	
}
console.log(people.name)
//P
function Car() {
	if(new.target !== Car) {
		throw Error("必须使用new来创建类")
	}
	if(!(this instanceof Car)) {
		throw Error("必须使用new来调用Car")
	}
}
ES5实现类
构造函数 √√√
function Car(speed,price) {
		this.speed = speed
		this.price = price
}
console.log(new Car(12,250000))
// Object.create(fn.prototype)
new到底发生了什么?
- 创建一个新对象
- 把构造函数的prototype属性 作为空对象的原型
- this赋值为这个空对象
- 执行函数
- 如果没有返回值 则返回this
function Contructor() {
	
}
第三方库的构造函数
学会写注释,最起码注释自己要能看懂
    (∩_∩)-----代码改变生活。
 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号