ES6面向对象(看完必有收获)

149 阅读1分钟

面向对象

  • 定义: 所谓的 面向对象编程 是 相对于 面向过程编程 而言的一种编程思想 编程方式 编程语法
// ES6面向对象编程 // 使用 class关键词 声明函数
class CreateObj2{
    // 通过 专门的构造器 声明定义属性属性值
    constructor( num1, num2 ){
        // 在 构造器constructor 中 设定 实例化对象的属性和属性值
        this.min = Math.min(num1, num2);
        this.max = Math.max(num1, num2);
    }
    // 直接定义函数名称 函数程序 
    // class关键词 会自动将 函数设定在 构造函数prototype中
    add () {
        let res = 0;
        for (let i = this.min; i <= this.max; i++) { res += i };
        return res;
    };
}
const obj2 = new CreateObj2( 1,100 );
console.log(obj2)
console.log(obj2.add())
// ES6面向对象语法
​
•        class 函数名称{
​
•          constructor( 参数1 , 参数2... ){
​
•              this.属性 = 参数1 ;
​
•              this.属性 = 参数2 ;
​
•          }
​
•          函数1(){} ;
​
•          函数2(){} ;
​
•        }
// ES5 面向对象编程(已经弃用)
​
// 设定一个构造函数 
function CreateObj1(num1, num2) {
    // 只设定实例化对象需要的属性属性值
    this.min = Math.min(num1, num2);
    this.max = Math.max(num1, num2);
};
// 在 函数.prototype 中设定 构造函数需要的函数方法
CreateObj1.prototype.add = function () {
    let res = 0;
    for (let i = this.min; i <= this.max; i++) { res += i };
    return res;
};
const obj1 = new CreateObj1( 1,100 );
console.log( obj1 );
// 工厂模式
// 设定一个函数 创建对象 返回对象
function createObj( num1 , num2 ){
    // 创建一个对象 
    const obj = {} ;
    // 给对象设定存储的属性属性值
    obj.min = Math.min( num1 , num2 );
    obj.max = Math.max( num1 , num2 ) ;
    // 给对象设定传参的函数程序
    obj.add = function(){
        let res = 0 ;
        for( let i = this.min ; i <= this.max ; i++ ){ res += i };
        return res ;
    }
    // 通过 return 返回这个对象
    return obj ;
}
const obj1 = createObj( 50 , 80 );
console.log( obj1 );
console.log( obj1.add() );
​
const obj2 = createObj( 60 , 20 );
console.log( obj2 );
console.log( obj2.add() );