实现类
1、使用原型
function Dog(name,legsNumber){
this.name = name
this.legsNumber = legsNumber
}
Dog.prototype.kind = '狗'
//私有属性放在构造函数中,共有属性放在 构造函数.prototype 上;
//非箭头函数 f:f.prototype.constructor = f
2、使用 class
class Dog{
constructor(name){
this.name = name
this.legsNumber = 4
}
tail = 1
static kind = '狗'
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
}
//constructor 里面放私有非函数属性,constructor 外面放共有的函数属性,非函数属性放在 constructor 外面相当于放在里面
//static 后面的属性是放在类 Dog 上,而不是在实例上
// ??原型上只能放函数,实例上只能放属性吗?
console.log(Dog.kind)
const d1 = new Dog('二哈')
d1.say()
继承和实例化
-
继承是两个类之间的关系,对象和类是实例化;
-
arr ==> Array ==> Object: arr 是 Array 的实例,拥有 Array.prototype 的属性;Array 继承了 Object;a 是 Object 的间接实例,a 拥有 Object.prototype 的属性
-
在 TS 中,用 class 实现继承
实现继承
使用原型链(ES5:没有 class、Object.create)
function Animal(legsNumber){
this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'
function Dog(name){
this.name = name
Animal.call(this,4) //调用父类构造函数,拥有父类的私有属性
}
Dog.prototype.__proto__ = Animal.prototype //绑定原型,拥有共有属性,因为各个浏览器的隐藏属性不同,
// 不一定都是 __proto__,所以这句代码不一定能用。
//替换代码,用下面的三句代替上面这一句
var f = function(){}
f.prototype = Animal.prototype
Dog.prototype = new f()
//原理:new 关键字会做5件事,这里需要的是第三件,将 Dog.prototype.__proto__ = f.prototype,
//但是又不需要第四件事,因为 Dog 构造函数中已经执行了父类的构造函数 Animal.call ,所以需要一个函数体为空的函数 f ,而不能直接 new Animal
//1、创建临时对象
//2、this = 临时对象
//3、this.__proto__ = 构造函数的 prototype
//4、执行构造函数
//5、return this(临时对象)
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~我是${this.name},我有${this.legsNumber}条腿`)
}
const d1 = new Dog('二哈')
console.dir(d1)
使用 class
class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber
}
run(){
console.log('run')
}
}
class Dog extends Animal{
constructor(name){
super(4) //执行 Animal 的构造函数,
this.name = name // constructor 里面的是私有属性,外面的是共有属性
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
}