面向对象、TS访问修饰符
1、面向对象编程是什么
它是用抽象的方式创建基于现实世界模型的编程模式(将数据和程序指令组合到对象中)
2、面向对象编程的目的
在编程中促进更好的灵活性和可维护性,在大型软件工程中广为流行。
3、面向对象编程的优势(继承、多态、封装)
继承:获取父类的全部(数据和功能),实现的是复制。
多态:根据实现方法的对象,相同方法名具有不同的行为。
封装:聚合对象数据和功能,以及限制它们和外界的联系(访问权限)。
JS中如何实现面向对象编程(参考)
1、原型链式继承
function Child() {} //子类
// Child.prototype.sleep=function(){
// console.log(this.name+"is sleeping")
// }1
Child.prototype = new Parent("yzh")
//为了不破坏原型链,将Male的constructor指向本身
Child.prototype.constructor=Child
Child.prototype.sleep=function(){
console.log(this.name+" is sleeping")
}//2
Parent.prototype.eat=function(){
console.log(this.name+" is eating")
}
var child=new Child()
console.log(Child)
child.introduce()
child.hobby("唱歌")
child.sleep()
child.eat()
console.log(child instanceof Parent) //true
console.log(child instanceof Child) //true
2、构造函数继承
function Child(name){
Parent.call(this,name)
}
var child=new Child("yzh")
console.log(child.name) //yzh
child.introduce()
child.hobby("sing")
console.log(child instanceof Parent) //false
console.log(child instanceof Child) //true
3、组合继承
function Child(name) {
Parent.call(this,name) //构造继承 ,第二次调用父类
}
//原型链继承
Child.prototype=new Parent()
Child.prototype.constructor=Child
var child=new Child("yzh") //子类的实例向父类传递参数,第一次调用父类
console.log(child.name)
child.introduce()
child.hobby("sing")
console.log(child instanceof Parent) //true
console.log(child instanceof Child) //true
4、寄生组合式继承
function Child(name) {
Parent.call(this,name) //构造继承
}
(function(){
//创建一个临时的类
var Temp=function(){}
Temp.prototype=Parent.prototype
//子类的原型指向父类的实例
Child.prototype=new Temp()
})()
var p=new Child("yzh")
console.log(p.name)//yzh
p.hobby("sing")//yzh like sing
p.introduce()//my name is yzh
5、class实现继承(参考)
class Parent{
constructor(name){
this.name=name
}
introduce(){
console.log("my name is " + this.name)
}
hobby(hobby){
console.log(this.name + " like " + hobby)
}
}
class Child extends Parent{
constructor(name,age){
super(name) //构造继承,可以继承Parent构造函数上的属性
this.age=age
}
}
var p = new Child("yzh")
p.introduce() //my name is yzh
p.hobby("apple")//yzh like apple
console.log(p instanceof Parent) // true
console.log(p instanceof Child) //true
TS访问修饰符有哪些
1、public:所有定义成public的属性和方法都可以在任何地方进行访问(公开)。
class Animal {
public age:number=10;
public run() {
console.log("这是一个跑的方法")
}
}
class Dog extends Animal{
}
let dog:Dog=new Dog()
dog.run() //继承过来的方法
dog.age=99; //继承过来的属性
console.log(dog.age)
2、private:所有定义成private的属性和方法都只能在类定义内部进行访问(私有的)。
class Animal {
private age:number=10;
private run() {
console.log("这是一个跑的方法")
}
}
class Dog extends Animal{
}
let dog:Dog=new Dog()
//dog.run() //属性“run”为私有属性,只能在类“Animal”中访问
//dog.age=99; //属性“age”为私有属性,只能在类“Animal”中访问
3、protected:多有定义成protected的属性和方法可以从类定义内部访问,也可以从子类中访问(受保护的)。
class Animal {
protected run() {
console.log("这是一个跑的方法")
}
}
class Dog extends Animal{
constructor(){
super()
super.run()
}
}
let dog:Dog=new Dog()
// dog.run() //属性“run”受保护,只能在类“Animal”及其子类中访问