原型模式

            function People(){}
            People.prototype.name="huanggabin";
            People.prototype.age=23;
            People.prototype.sayName=function  () {
                console.log(this.name);
            }
            var a=new People();
            var b=new People();
            console.log(a.name,a.age,b.name,b.age,a.name==b.name,b.sayName()==a.sayName());
            b.sayName();

这里的a,b实例的数据都是一样的

var a={};//不能用字面量方法定义

判断原型函数和实例是否匹配

console.log(People.prototype.isPrototypeOf(a),People.prototype.isPrototypeOf(b));

实例返回对象原型

Object.getPrototypeOf(a)

用delete可以消除实例对原型的屏蔽

检查实例a是否有自己的name属性

a.hasOwnProperty("name")

检查实例或原型函数是否有自己的name属性

"name" in a

返回包含所有可枚举属性的字符串数组,若是实例,就返回实例的,不包含原型的

var c=Object.keys(People.prototype);

 重写原型对象之后的实例和原型对象不能连接


由于原型对象全部实例共享,但对有引用类型(数组之类来说有点不友好,比较我目测每个实例都需要自己的引用数组

a.friend.push("xiaoming");

b.friend//变了和a一样 

我有有几种方法

组合使用构造函数和原型函数模式

            function Person (name,age) {
                this.name=name;
                this.age=age;
                this.friends=["gabing","sb"];
            }
            Person.prototype={
                constructor:Person,
                sayName:function(){
                    console.log(this.name);
                }
            }
            var a=new Person("huangyucheng",20);
            var b=new Person("huangzhiming",20);
            a.friends.push("fucker");
            console.log(a.friends,b.friends);

寄生构造函数模式

比工厂函数多了new

            function SpecialArray () {
                var a=new Array();
                a.push.apply(a,arguments);
                a.specialPrint=function(){
                    return this.join("|");
                }
                return a;
            }
            var a=new SpecialArray("huanggabin","huangzhiming");
            console.log(a.specialPrint());

他的目的是为了不污染原生的array,来创建一个特殊的special Array


稳妥构造函数模式

有点像封装的意思

            function SpecialArray () {
                var a=new Array();
                a.push.apply(a,arguments);
                a.specialPrint=function(){
                    return this.join("|");
                }
                return a;
            }
            var a=new SpecialArray("huanggabin","huangzhiming");
            console.log(a.specialPrint());
原文地址:https://www.cnblogs.com/vhyc/p/5771517.html