1.简单工厂模式 :无法确定对象类型 2.构造函数模式 :私有话的问题 3.原型模式
// 1简单工厂模式 function CreatPerson(name,age,sex){ var obj=new Object(); obj.name=name; obj.age=age; obj.sex=sex; obj.sayName=function(){ console.log("姓名:"+this.name+" 年龄:"+this.age+" 性别:"+this.sex); }; return obj; } var person1=CreatPerson("iwen",20,"男人"); person1.sayName(); var person2=CreatPerson("ime",22,"女人"); person1.sayName(); /* * 函数CreatePerson能够根绝传入的参数构建不同的对象,并且可以保存对象的必要信息 * 每一个对象保存的信息都是独立的。 * 问题:person1和person2对象能知道是什么类型么?他属于谁? * * typeof instanceof * * */ /* * * 构造函数模式 * 在javascript中,构造函数可以用来创建特定类型的对象 * Object,Array本身用的就是构造函数模式创建的 * * */ function Person(name,age,sex){ this.name = name; this.age = age; this.sex =sex; this.sayName = function(){ console.log("姓名:"+this.name+" 年龄:"+this.age+" 性别:"+this.sex); } } var person1 = new Person("iwen","19.8","男"); var person2= new Person("ime","200.8","男"); person1.sayName(); person2.sayName(); // * 在当前这个例子中,Person取代了CreatePerson,Person中的代码// * 除了与CreatePerson中相同的部分,不同的点// * 1.没有显示的创建对象// * 2.直接将属性和方法赋值给this对象// * 3.没有return对象// *// * 在构造函数中,我们需要使用关键字new去创建对象// * 在我们通过new创建对象的时候,会经历四个步骤// * 1.创建新的对象// * 2.将构造函数的作用域赋值给新的对象// * 3.执行构造函数中的代码(为这个新的对象添加属性和方法)// * 4.返回新的对象// *// * person1 和 person2 两个对象都有一个constructor(构造函数),而且这个属性都指向Person// *// *// * 只有构造函数才存在constructor ////// * 任何函数只要通过关键字new来调用,都可以看成是构造函数模式// * 任何函数也都可以通过赋值的形式进行调用 /* * * 原型模式: * * */ function Person(name,age){ this.name = name; // 私有属性和方法 this.age = age; this.oldSayName = function(){ } } //并没有挂载在window身上,而是挂载原型身上 Person.prototype.sayName = function(){ //公共方法 console.log("姓名:"+this.name+" 年龄:"+this.age); }; var person1 = new Person("iwen","20"); var person2 = new Person("heihie","21"); // person1.sayName(); // person2.sayName(); Person.prototype.sex = "男"; person1.sex = "女"; console.log(person1.sex); console.log(person2.sex); console.log(person1.sayName === person2.sayName); console.log(person1.oldSayName === person2.oldSayName); console.log(person1.sex === person2.sex); //原型模式还是存在一定的问题,如果存在多个原型链,可以继续优化 function Fn(num1,num2){ this.num1=num1; this.num2=num2; } var pro=Fn.prototype; console.log(pro); Fn.prototype={ num3:function(){ console.log("我是三"); }, num4:function(){ console.log("我是四"); }, reset:function(){ for(var key in pro){ this[key]=pro[key]; } }, constructor:Fn }; console.log( Fn.prototype);
时间: 2024-07-28 14:10:52