面向对象的一些简单设计

为了方便使用,防止污染全局变量,可以把一系列功能封装在一个类中使用

const CheckObj1 = function(){
    this.checkName = function(){
        console.log("checkName")
    }
    this.checkEmail = function(){
        console.log("checkEmail")
    }
    this.checkPassword = function(){
        console.log("checkPassword")
    }
}

但上述做法,每次实例化CheckObj时, 实例对象都会复制一份this上的方法, 会产生多余的消耗,可以使用原型链的特性,让所有的实例对象共用一套方法

这样,所有的实例对象就都会使用原型中的方法而不会单独创建了

ps:定义在原型上的必须在实例对象中使用

const CheckObj2 = function(){}
CheckObj2.prototype.checkName = function(){
    console.log("checkName")
}
CheckObj2.prototype.checkEmail = function(){
    console.log("checkEmail")
}
CheckObj2.prototype.checkPassword = function(){
    console.log("checkPassword")
}

可以批量创建原型方法,并且当返回为this时,可实现链式调用

const CheckObj3 = function(){}
CheckObj3.prototype = {
    checkName: function(){
        console.log("checkName")
        return this
    },
    checkEmail: function(){
        console.log("checkEmail")
        return this
    },
    checkPassword: function(){
        console.log("checkPassword")
        return this
    }
}
let b = new CheckObj3()
b.checkName().checkEmail().checkPassword()

 

posted @ 2021-11-26 22:09  邢韬  阅读(43)  评论(0编辑  收藏  举报