JavaScript simple factory pattern

Js factory mode: Encapsulate classes with the same characteristics in a function, so that the required objects can be created only through this function.

<script type="text/javascript">
			//总体的类型   工厂模式把所有的属性和方法写在一块
			function createObject(name,age){
				var obj = new Object();
				obj.name = name;
				obj.age = age;
				obj.sayHello = function(){
					console.log(this.name);
				}
				return obj;
			}
			
			var student1 = createObject("john1",20);
			var student2 = createObject("john2",20);
			
			var miaomaio = createObject("xiaohua",2);
			miaomaio.sayHello();
			//instanceof 判断一个对象是不是某个类型的实例
			console.log(student1 instanceof Object);//true
			console.log(miaomaio instanceof Object);//true
</script>

Guess you like

Origin blog.csdn.net/qq_42697806/article/details/127262990