小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
面向对象编程
面向过程编程POP
分析步骤,再按照步骤实现 性能高,但维护难
面向对象编程OOP
先找对象,把事物分解成对象,对象之间分工合作 适合多人合作,性能低一点,适合维护和复用 特性:封装性,继承性,多态性
ES6中的类和对象
- 对象由属性和方法组成,是一个具体的事物
- 类用class声明,抽象了对象的公共部分
- 创建类
class star{
}
new star();
- 类constructor构造函数 用于传递参数,返回实例对象,new生成对象时自动调用constructor函数,自己不写会自动生成 定义类的时候首字母大写
class star{
constructor(usname,age){
this.usname = usname;
this.age = age;
}
}
let ldh = new star('hello',100)
console.log(ldh.usname);
console.log(ldh.age);
console.log(ldh);
- 类添加方法
class star{
constructor(usname,age){
this.usname = usname;
this.age = age;
}
sing(n) {
console.log(n);
}
}
let ldh = new star('hello',100)
ldh.sing('helloworld')
类的继承
extends关键字继承父类 super关键字可以调用父类的构造函数,也可以调用父类的普通函数 this指向当前实例对象,当前调用的对象
!!!错误代码
class Father{
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x+this.y);
}
}
class Son extends Father{
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let mi = new Son(1, 2);
mi.sum();
!!!正确的
class Father{
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x+this.y);
}
}
class Son extends Father{
constructor(x, y) {
super(x,y)
}
}
let mi = new Son(1, 2);
mi.sum();
继承父类的同时要实现子类添加自己的方法的话怎么办
class Father{
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x+this.y);
}
}
class Son extends Father{
constructor(x, y) {
super(x, y)//super()方法必须要调用在this之前
this.x = x;
this.y = y;
}
submact() {
console.log(this.x-this.y);
}
}
let mi = new Son(1, 2);
mi.sum();
mi.submact();
<body>
<button>yes</button>
<script>
class star{
constructor(usname){
this.usname = usname;
this.btn = document.querySelector('button');
this.btn.onclick = this.sing;//这里的sing不要加()不然会执行一次
}
sing(){
console.log(this.usname);
}
}
let ldh = new star('hello')
</script>
</body>