首页 > Web开发 > 详细

JS高级:面向对象的构造函数

时间:2019-09-30 23:24:04      阅读:103      评论:0      收藏:0      [点我收藏+]

1 创建对象的方式

1.1 字面量的方式创建对象

    var p1 = {
        name: '张三',
        run: function () {
           console.log(this.name + '跑');
        }
    };

    var p2 = {
        name: '李四',
        run: function () {
            console.log(this.name + '跑');
        }
    };

    console.log(p1.name);
    p1.run();

    console.log(p2.name);
    p2.run();

1.2 内置构造函数的方式

    var p1 = new Object();
    p1.name = '张三';
    p1.run = function () {
        console.log(this.name + '跑');
    }

问题:使用内置构造函数的方式和字面量的方式来创建对象差不多,都存在以下问题:

  • 创建的对象无法复用,复用性差
  • 如果需要创建多个同类型的对象,如(书籍)则需要写大量重复的代码,代码的冗余度高

    1.3 简单工厂的方式

function createPerson(name){
    var obj=new Object();//1.原料
    //2.加工
    obj.name=name;
    obj.showName=function(){
    alert(this.name);
    }
    return obj;//3.出厂
}

工厂里面有一些产品的模板, 只需要, 给工厂提供原材料; 工厂按照固定的加工方式, 就可以返回给外界同一类型的产品

问题:无法判定类型

1.4 自定义构造函数方式

1.4.1 普通

    function Dog(name, age, dogFriends) {
        // 属性
        this.name = name;
        this.age = age;
        this.dogFriends = dogFriends;

        // 行为
        this.eat = function (someThing) {
            console.log(this.name + '吃' + someThing);
        };

        this.run = function (someWhere) {
            console.log(this.name + '跑' + someWhere);
        }
    }

    // 产生对象
    var smallDog = new Dog('小花', 1);
    console.log(smallDog.name, smallDog.age);
  1. 函数的首字母大写(用于区别构造函数和普通函数)
  2. 创建对象的过程是由new关键字实现
  3. 在构造函数内部会自动的创建新对象,并赋值给this指针
  4. 自动返回创建出来的对象

1.4.2 参数优化

    function Dog(options) {
        // 属性
        this.name = options.name;
        this.age = options.age;
        this.dogFriends = options.dogFriends;

        // 方法
        this.eat = function (someThing) {
            console.log(this.name + '吃' + someThing);
        };

        this.run = function (someWhere) {
            console.log(this.name + '跑' + someWhere);
        }
    }

1.4.3 改进

    function Dog(option) {
        // 属性
        this.name = option.name;
        this.age = option.age;
        this.dogFriends = option.dogFriends;
    }

    Dog.prototype.eat = function (someThing) {
        console.log(this.name + '吃' + someThing);
    };

    Dog.prototype.run = function (someWhere) {
        console.log(this.name + '跑' + someWhere);
    };

1.4.4 最后版

 function Dog(option) {
        this._init(option)
    }

    Dog.prototype = {
        _init: function(option){
            // 属性
            this.name = option.name;
            this.age = option.age;
            this.dogFriends = option.dogFriends;
        },

        eat: function (someThing) {
            console.log(this.name + '吃' + someThing);
        },

        run: function (someWhere) {
            console.log(this.name + '跑' + someWhere);
        }
    };

JS高级:面向对象的构造函数

原文:https://www.cnblogs.com/tangge/p/11614480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!