7、JS如何实现类?
两种方法:
ES6之前没有class.
那为什么要有类?
第一批前端好多都是java转的,他们按照java的写法写JS。
java程序员不允许没有类。
方法一:使用原型
对象本身的属性写在构造函数里面,把共有属性写在原型上面。
function Dog(name){
this.name = name
this.legsNumber = 4
}
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
Dog.prototype.run = function(){
console.log(`${this.legsNumber}条腿跑起来。`)
}
const d1 = new Dog('啸天') // Dog 函数就是一个类
d1.say()
原型的错误写法
Dog.prototype = {
say:...
kind:....
}
不对 因为JS本身内置一个 Dog.prototype.constructor = Dog,在某些时候会影响代码逻辑。
任何一个函数的prototype.constructor,都等于这个函数本身,除了箭头函数。
这样你声明d1 你就不知道它是谁构造出来的。
方法二:使用class
class Dog {
kind = '狗' // 等价于在 constructor 里写 this.kind = '狗' 也是自身属性
constructor(name) {
this.name = name
this.legsNumber = 4
// 思考:kind 放在哪,放在哪都无法实现原型上面的一样的效果(写在原型上)
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
run(){
console.log(`${this.legsNumber}条腿跑起来。`)
}
}
const d1 = new Dog('啸天')
d1.say()
constructor里面放自身属性,外面放共有属性。TS中使用class.
7、JS如何实现继承?
继承就是类和类之间的关系一个类继承了另一个类
方法一:使用原型链
两个关键点,
自身属性要继承
Animal.call,并传this和参数
共有属性要继承。
Dog.prototype.proto = Animal.prototype /
如果被禁用就使用下面三行代替
function Animal(legsNumber){
this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'
function Dog(name){
this.name = name
Animal.call(this, 4) // 关键代码1,继承构造属性,调用构造函数。相当于 this.lengsNumber = 4
}
Dog.prototype.__proto__ = Animal.prototype // 关键代码2,就是组建一个原型链但这句代码被禁用了,怎么办
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
const d1 = new Dog('啸天') // Dog 函数就是一个类
console.dir(d1)
关键点二被禁用解决方法:
Dog.prototype = new Animal()
new做了五件事
1、创建临时对象
2、this = 临时对象
3、this.proto = 构造函数的prototype //我么主要用这一步去改造他的原型
4、执行构造函数 //由于空了所以第四步不生效 就不会给他加腿
5、return this
由于Animal构造函数 构造出来的实例拥有Animal的所有属性和方法。
但是,我上面的legsNumber已经实现继承 了 我不需要
所以新建一个空的函数,让这个函数的prototype = Animal.prptotype
然后使用f来new
如果面试官问被 ban 的代码如何替换,就说下面三句:
var f = function(){ }
f.prototype = Animal.prototype
Dog.prototype = new f()
方法二 class
两部
1、extends 共有属性会自动上去
2、super (构造函数中使用super,会自动执行Animal constructor中的代码)
super放在第一行
class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber
}
run(){}
}
class Dog extends Animal{
constructor(name) {
super(4)
this.name = name
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
}