【JavaScript】原生js内容之面向对象工厂模式优化

工厂模式

    function createPerson(name, qq) { //构造函数-工厂方式
        var obj = new Object() //原料
        //加工
        obj.name = name
        obj.qq = qq
        obj.showName = function () {
            alert(this.name)
        }
        obj.showQQ = function () {
            alert(this.qq)
        }
        //出厂
        return obj
    }
    var obj = createPerson('wen', '244200')
    obj.showName()
    obj.showQQ()

函数和new

    function show(){
        alert(this)
    }
    show() //window
    new show() //object 新 NEW 出来的对象

优化工厂模式没有 new 的问题

    function createPerson(name, age) {
        //var this = new Object();
        //new 函数,系统会自动定义一个空白对象
        this.name = name
        this.age = age
        this.showName = function () {
            alert(this.name)
        }
        this.showAge = function () {
            alert(this.age)
        }
        //系统会自动将对象返回出去
        //return this
    }
    var obj = new createPerson('wen', 32)
    obj.showName()
    obj.showAge()

原型

    var arr = new Array(10,20,30,40)
    var arr2 = new Array(10,20,30)
    //arr.sum = function(){    //相当于行间样式,给对象加东西一次只对一个对象起作用
        Array.prototype.sum = function(){  //这是 js 里的原型,可以一次给一组对象加东西,加到类上
        var result = 0
        for(var i = 0; i < this.length; i++){
            result = result + this[i]
        }
        return result
    }
    alert(arr.sum())
    alert(arr2.sum())

类:模子  var arr = new Array()  Array 就叫做类

对象:产品 var arr = new Array() arr 就叫做对象

混合方式构造对象

<script>
    function CreatePerson(name, age) {
        this.name = name //构造函数里加属性
        this.age = age
    }
    CreatePerson.prototype.showName = function () { //原型里加方法
        alert(this.name)
    }
    CreatePerson.prototype.showAge = function () {
        alert(this.age)
    }
    var obj = new CreatePerson('wen', 32)
    var obj2 = new CreatePerson('wen2', 322)
    alert(obj.showName == obj2.showName) //通过原型方式,避免了工厂方式函数重复,占用空间的问题
</script

猜你喜欢

转载自blog.csdn.net/meichaoWen/article/details/113752576
今日推荐