原型设计模式以及JavaScript中的原型规则

1,193 阅读2分钟

1. 原型设计模式以及JavaScript中的原型规则

原型规则

1. 所有的引用类型都有对象的特性,即可自由扩展
2. 所有的引用类型都有一个_proto_属性(隐式原型),属性的值是一个普通对象
3. 所有的函数都有一个prototype属性(显式原型),属性值也是一个普通对象
4. 所有的引用类型,其隐式原型指向其构造函数的显式原型
5. 当试图得到一个对象的某个属性时,如果这个对象本身没有这个属性,那么回去它的_proto_(即它的构造函数的prototype)中去寻找

原型链

定义:在JS中如果想访问某个对象(实例)的属性,首先会在对象内部寻找,如果没找到,则会去它的_proto_(即隐式原型)上查找,也就是它的构造函数的prototype(显式原型)上查找,如果没找到,则会继续在构造函数的prototype的_proto_上查找,这样一层一层向上查找形成的链式结构称为原型链

设计模式

  • 工厂模式

在函数内创建一个对象,给对象赋予属性及方法再将对象返回

function Person() {
    var info = new Object()
    info.name = '张三'
    info.age = 18
    info.sex = function() {
        return 'boy'
    }
    return info
}
let p1 = Person()
console.log(p1.name) // '张三'
console.log(p1.sex()) // 'boy'
  • 构造函数模式

无需在函数内部重新创建对象,而是用this指代

function Person() {
	this.name = 'CrazyLee';
	this.age = '25';
	this.sex = function(){
		return 'boy'
	};
}
var a = new Person();
console.log(a.name);//CrazyLee
console.log(a.sex());//boy
  • 原型模式

函数中不对属性进行定义,利用prototype属性对属性进行定义,可以让所有对象实例共享它所包含的属性及方法

function Parent() {
    Parent.prototype.name = 'carzy';
    Parent.prototype.age = '24';
    Parent.prototype.sex = function() {
        var s="女";
        console.log(s);
    }
}

    var x = new Parent();
    console.log(x.name);      //crazy
    console.log(x.sex());       //女
  • 混合模式

原型模式+构造函数模式。这种模式中,构造函数模式用于定义实例属性,而原型模式用于定义方法和共享属性

function Parent(){  
	this.name="CrazyLee";  
	this.age=24;  
};
Parent.prototype.sayname=function(){  
	return this.name;  
};

var x =new Parent(); 
console.log(x.sayname());   //Crazy  

  • 动态原型模式

将所有信息封装在了构造函数中,而通过构造函数中初始化原型,这个可以通过判断该方法是否有效而选择是否需要初始化原型。

function Parent(){  
	this.name="CrazyLee";  
	this.age=24;  
	if(typeof Parent._sayname=="undefined"){     
		Parent.prototype.sayname=function(){  
			return this.name;  
		}  
		Parent._sayname=true;  
	}         
};   

var x =new Parent();  
console.log(x.sayname());