构造函数与原型

构造函数与原型_第1张图片
面向对象.png
//工厂模式
            function People (name,age) {
                var obj = {};
                obj.name = name;
                obj.age = age;
                
                obj.say = function () {
                    return '我的名字是:'+ obj.name + '今年:'+obj.age;
                }
                return obj;
            }
            console.log('工厂模式--------------------------');
            //实例1
            var ming = People('小明',10);
            console.log(ming.say());
            //实例2
            var hua = People('小花',9);
            console.log(hua.say());
            
            
            //构造函数
            function createPeople (name,age) {
                //私有属性
                this.name = name;
                this.age = age;
                
                //私有方法
                this.say = function () {
                    return '我的名字:' + this.name + '我的年龄:' + this.age;
                }
            }
            console.log('构造函数--------------------------');
            //实例1
            var xiaoming = new createPeople('小王',12);
            console.log(xiaoming.say());
            
            //原型模式
            function creatThePeople (name,age) {
                this.name = name;
                this.age = age;
            }       
            
            //将公有方法放到函数的原形链上
            creatThePeople.prototype.say = function () {
                return '我的名字:' + this.name + '我的年龄:' + this.age;
            }
            
            
            console.log('原型模式--------------------------');
            //实例1
            var person1 = new creatThePeople('张三',30);
            console.log(person1.say());
            console.log(person1);
            var person2 = new creatThePeople('李四',28);
            console.log(person2.say());
            console.dir(person2);
            console.dir(new creatThePeople('asas',13));

你可能感兴趣的:(构造函数与原型)