在平时开发时,我们会遇到要创建许多类型相似的object,之前的文章有提到使用new操作符配合function可以达到我们的需求,而今天要介绍的是Class。
calss ownClass {
constructor() {}
method1() {}
method2() {}
method3() {}
}
实际举个例子说明new class的一些观念:
class Cat {
constructor(name) {
this.name = name
}
jump() {
console.log(`${this.name} jump!`)
}
eat() {
console.log(`${this.name} eat!`)
}
}
let catA = new Cat("CatA");
console.log(typeof Cat); // function
console.log(Cat === Cat.prototype.constructor) // true
console.log(Cat.prototype.jump) // console.log(`${this.name} jump!`)
console.log(Object.getOwnPropertyNames(Cat.prototype)) // ["constructor", "jump", "eat"]
许多文章都认为class只是语法糖,可以用一般的构造器重复写出相同於上面Cat的功能:
function Cat(name) {
this.name = name
}
Cat.prototype.jump = function() {
console.log(`${this.name} jump!`)
}
Cat.prototype.eat = function() {
console.log(`${this.name} eat!`)
}
let catA = new Cat("CatA");
构造器与Class差别:
与函数一样有声明与表达式两种,上面介绍的是声明式,以下是表达式的例子:
let Cat = class {
jump() {
console.log(`${this.name} jump!`)
}
}
类似於函数的具名表达式,Class也有,不过只在函数内可见:
let Cat = class CatClass {
jump() {
console.log(`${this.name} jump!`)
}
getClassName() {
console.log(CatClass)
}
}
let catA = new Cat;
catA.getClassName(); class CatClass{...}
console.log(CatClass); // CatClass is not defined
class Cat {
constructor(name) {
this.name = name
}
get name() {
return this._name
}
set name(value) {
this._name = value
}
}
let catA = new Cat("catA");
console.log(catA.name); // catA
catA.name = 'catB';
console.log(catA.name) // catB
在Class中新增的属性会独立的在每个object中新增,而不是新增在prototype中。
class Cat {
name = "catA";
jump() {
console.log(`${this.name} jump!`)
}
}
new Cat().jump(); // catA jump!
新增属性也可以作为Day11函数绑定的一个解法:
class Cat {
constructor(name) {
this.name = name
}
jump() {
console.log(`${this.name} jump!`)
}
}
let catA = new Cat("catA");
setTimeout(catA.jump,1000) // undefined
可以运用箭头函数的特性,this会指向父作用域的this,在下面的例子中就会指向Cat这个function的this,也就会指向catA。
class Cat {
constructor(name) {
this.name = name
}
jump = () => {
console.log(`${this.name} jump!`)
}
}
let catA = new Cat("catA");
setTimeout(catA.jump,1000) // catA jump!
<<: [Day16]What is Merkle tree?
routing 在介绍完model验证之後要开始介绍网页程序设计的另一个观念路由routing,更明...
购物车後端的部分终於要结束啦~ 以下内容有参考教学影片,底下有附网址。 (内容包括我的不专业解说分析...
还记得区域元件有自己的作用域吗?已知外层元件可以跟内层元件传递资料(props),或是传递事件(em...
前面我们使用 RTCPeerConnection.addTrack() 来把我们的音视讯传送给对方 ...
PostgreSQL是一个开源的框架,关联式资料库资管理系统。PostgreSQL 的操作过程相似於...