Javascript 面向对象编程

如何开发前端框架源码
ui前端开发框架有哪些
对前端开发的框架

一. js 声明类常见方式
javascript 代码

<script type=”text/javascript”>
    /**
     * 创建类的方法
     * 在JavaScript中, 当你定义了一个新的函数, 你实际上声明了一个新的类, 而这个函数本身就相当于类的构造函数。
     * 在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称”实例”)共有的属性和方法。
     Javascript语言不支持”类”,但是可以用一些变通的方法,模拟出”类”。
     * 1. 构造函数模式 prototype
     * 缺点是,比较复杂,用到了this和prototype,编写和阅读都很费力。
     *
     * 2. Object.create()法
     *
     * 3. 极简主义法:1>方便实现继承 2>继承实现中又可以声明 私有属性和私有方法 3>共享数据
     */
    function Tree(element, options) {
        this.$element = $(element);
        this.$tree = this.$element.closest(“.tree”);
    }
    //Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。
    Tree.prototype = {
        constructor: Tree,
        foo1: function () {
            //class function
        },
        foo2: function () {
            //class function
        }
    }
    function CatConstructor(name, color) {
        this.name = name;
        this.color = color;
    }
    var cat_con = new CatConstructor(“大花”, “白色”);
    var cat_con2 = new CatConstructor(“小黑”, “黑色”);
    console.log(cat_con.constructor == CatConstructor);//cat_con 对象会自动含有一个constructor属性,指向它们的构造函数。
    console.log(cat_con2.constructor == CatConstructor)//true
    //Javascript还提供了一个instanceof运算符,验证原型对象与实例对象之间的关系。
    console.log(cat_con instanceof CatConstructor);
    //但是存在一个浪费内存的问题。但是可以通过prototype模式解决
    //avascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
    //这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。
    //或者
    //类的属性和方法,还可以定义在构造函数的prototype对象之上
    var Calendar = function (element) {
        this.$element = $(element);
    };
    Calendar.prototype.get = function () {
        // body…
    };
    Calendar.prototype.set = function () {
        // body…
    };
    //prototype 实现继承
    //如果”猫”的prototype对象,指向一个Animal的实例,那么所有”猫”的实例,就能继承Animal了
    //Cat.prototype = new Animal();//Cat.prototype = new Animal();Cat.prototype.constructor = Cat;
    //Cat.prototype.constructor = Cat;//将Cat.prototype对象的constructor值改为Cat
    //3.1 封装
    //这种方法不使用this和prototype,代码部署起来非常简单,这大概也是它被叫做”极简主义法”的原因。
    //首先,它也是用一个对象模拟”类”。在这个类里面,定义一个构造函数createNew(),用来生成实例。
    //然后在createNew 里面定义一个实例帝乡,吧这个实例对象作为返回值
    //这种方法的好处是,容易理解,结构清晰优雅,符合传统的”面向对象编程”的构造,因此可以方便地部署下面的特性。
    var Cat = {
        createNew: function (name, sex) {
            //some code here
            var cat = {};
            cat.name = name;
            cat.makeSound = function () {
                alert(“喵喵喵”);
            };
            return cat;
        }
    };
    var cat1 = Cat.createNew();
    cat1.makeSound();
    //3.2 继承 Cat 继承Animal类
    //让一个类继承另一个类,实现起来很方便。只要在前者的createNew()方法中,调用后者的createNew()方法即可。
    //先定义Animal类
    //然后在Dog的createNew方法中,调用Animal的createNew方法
    var Animal = {
        createNew: function () {
            var animal = {};
            animal.sleep = function () {
                alert(“睡懒觉”);
            }
            return animal;
        }
    }
    var Dog = {
        createNew: function (name, sex) {
            //some code here
            var dog = Animal.createNew();
            dog.name = name;
            dog.sex = sex;
            dog.makeSound = function () {
                alert(“汪汪汪”);
            };
            return dog;
        }
    };
    var dog1 = Dog.createNew();
    dog1.sleep();//睡懒觉
    //3.3 私有属性和私有方法
    //在createNew()方法中,只要不是定义在cat对象上的方法和属性,都是私有的。
    var sheep = {
        createNew: function () {
            var sheep = {};
            var sound = “咩咩咩”;
            sheep.makeSound = function () {
                alert(sound);
            }
            return sheep;
        }
    }
    //上例的内部变量sound,外部无法读取,只有通过cat的公有方法makeSound()来读取。
    var sheep1 = sheep.createNew();
    sheep1.makeSound();
    //3.4 数据共享
    //有时候,我们需要所有实例对象,能够读写同一项内部数据。这个时候,只要把这个内部数据,封装在类对象的里面、createNew()方法的外面即可。
    var Student = {
        class: “三年级”,
        createNew: function () {
            var stu = {};
            stu.getGrade = function (id) {
                alert(Student.class);
            }
            stu.UpdateClass = function () {
                Student.class = “四年级”;
            }
            return stu;
        }
    }
    var stu1 = Student.createNew();
    var stu2 = Student.createNew();
    stu1.getGrade(1);
//这时,如果有一个实例对象,修改了共享的数据,另一个实例对象也会受到影响
</script>

二、Javascript 面向对象编程(二):封装

三、Javascript 面向对象编程(三):构造函数的继承

四、Javascript 面向对象编程(四):非构造函数的继承

五、js中prototype用法详细介绍 对已有方法的实现和增强 和其他实际用处

   例子1:通过prototype 修改内置对象的原型
   **javascript 代码**
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn) {
        for (var i = 0; i < this.length; i++) {
            fn(this[i], i, this)
        }
    }
}
;[‘a’, ‘b’, ‘c’].forEach(function(value, index, array) {
    assert(value, ‘Is in position ‘ + index + ‘ out of ‘ + (array.length – 1))
})

如果不是有特殊需要而去扩展原生对象和原型(prototype)的做法是不好的,但是我们可以用原型扩展对象
参考文档:https://segmentfault.com/a/1190000002634958#articleHeader3

  1. String对象的扩展
    javascript 代码
<script type=”text/javascript”>
    if (typeof String.prototype.ltrim == ‘undefined’) {
        String.prototype.ltrim = function () {
            var s = this;
            s = s.replace(/^\s*/g, ”);
            return s;
        }
    }
    if (typeof String.prototype.rtrim == ‘undefined’) {
        String.prototype.rtrim = function () {
            var s = this;
            s = s.replace(/\s*$/g, ”);
            return s;
        }
    }
    if (typeof String.prototype.trim == ‘undefined’) {
        String.prototype.trim = function () {
            return this.ltrim().rtrim();
        }
    }
    if (typeof String.prototype.htmlEncode == ‘undefined’) {
        String.prototype.htmlEncode = function (encodeNewLine) {//encodeNewLine:是否encode换行符
            var s = this;
            s = s.replace(/&/g, ‘&amp;’);
            s = s.replace(/</g, ‘&lt;’);
            s = s.replace(/>/g, ‘&gt;’);
            s = s.replace(/’/g, ‘&quot;’);
            if (encodeNewLine) {
                s = s.replace(/\r\n/g, ”);
                s = s.replace(/\r/g, ”);
                s = s.replace(/\n/g, ”);
            }
            return s;
        }
    }
</script>

2.Date 对象的扩展 getDaysInMonth:获取某月有多少天
javascript 代码

Date.getDaysInMonth = function(year, month) {
    var days = 0
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            days = 31
            break
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30
            break
        case 2:
            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) days = 29
            else days = 28
            break
    }
    return days
}
if (typeof Date.prototype.format == ‘undefined’) {
    Date.prototype.format = function(mask) {
        var d = this
        var zeroize = function(value, length) {
            if (!length) length = 2
            value = String(value)
            for (var i = 0, zeros = ”; i < length – value.length; i++) {
                zeros += ‘0’
            }
            return zeros + value
        }
        return mask.replace(
            /”[^”]*”|'[^’]*’|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g,
            function($0) {
                switch ($0) {
                    case ‘d’:
                        return d.getDate()
                    case ‘dd’:
                        return zeroize(d.getDate())
                    case ‘ddd’:
                        return [‘Sun’, ‘Mon’, ‘Tue’, ‘Wed’, ‘Thr’, ‘Fri’, ‘Sat’][d.getDay()]
                    case ‘dddd’:
                        return [
                            ‘Sunday’,
                            ‘Monday’,
                            ‘Tuesday’,
                            ‘Wednesday’,
                            ‘Thursday’,
                            ‘Friday’,
                            ‘Saturday’,
                        ][d.getDay()]
                    case ‘M’:
                        return d.getMonth() + 1
                    case ‘MM’:
                        return zeroize(d.getMonth() + 1)
                    case ‘MMM’:
                        return [
                            ‘Jan’,
                            ‘Feb’,
                            ‘Mar’,
                            ‘Apr’,
                            ‘May’,
                            ‘Jun’,
                            ‘Jul’,
                            ‘Aug’,
                            ‘Sep’,
                            ‘Oct’,
                            ‘Nov’,
                            ‘Dec’,
                        ][d.getMonth()]
                    case ‘MMMM’:
                        return [
                            ‘January’,
                            ‘February’,
                            ‘March’,
                            ‘April’,
                            ‘May’,
                            ‘June’,
                            ‘July’,
                            ‘August’,
                            ‘September’,
                            ‘October’,
                            ‘November’,
                            ‘December’,
                        ][d.getMonth()]
                    case ‘yy’:
                        return String(d.getFullYear()).substr(2)
                    case ‘yyyy’:
                        return d.getFullYear()
                    case ‘h’:
                        return d.getHours() % 12 || 12
                    case ‘hh’:
                        return zeroize(d.getHours() % 12 || 12)
                    case ‘H’:
                        return d.getHours()
                    case ‘HH’:
                        return zeroize(d.getHours())
                    case ‘m’:
                        return d.getMinutes()
                    case ‘mm’:
                        return zeroize(d.getMinutes())
                    case ‘s’:
                        return d.getSeconds()
                    case ‘ss’:
                        return zeroize(d.getSeconds())
                    case ‘l’:
                        return zeroize(d.getMilliseconds(), 3)
                    case ‘L’:
                        var m = d.getMilliseconds()
                        if (m > 99) m = Math.round(m / 10)
                        return zeroize(m)
                    case ‘tt’:
                        return d.getHours() < 12 ? ‘am’ : ‘pm’
                    case ‘TT’:
                        return d.getHours() < 12 ? ‘AM’ : ‘PM’
                    case ‘Z’:
                        return d.toUTCString().match(/[A-Z]+$/)
                    // Return quoted strings with the surrounding quotes removed
                    default:
                        return $0.substr(1, $0.length – 2)
                }
            },
        )
    }
}

参考文档:JavaScript原生对象及扩展

原生拷贝对象
html 代码

function (target, source) {
    for (var p in source) {
        if (source.hasOwnProperty(p)) {
            target[p] = source[p];
        }
    }
    return target;
}
前端混合app开发框架
手机web前端开发框架
前端开发的主流框架有哪些
» 本文来自:前端开发者 » 《Javascript 面向对象编程》
» 本文链接地址:https://www.rokub.com/6250.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!